-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
125 lines (99 loc) Β· 2.16 KB
/
main.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#include <stdlib.h>
#include <stdio.h>
// Structure for stack
struct Stack{
int size;
int top;
int *s;
};
// ADT stack
// 1. isEmpty
int isEmpty(struct Stack *st){
if(st->top == -1){
return 1; // 1 true
}
return 0; // false
}
// 2. isFull
int isFull(struct Stack *st){
if(st->top == st->size-1){
return 1;
}
return 0;
}
// stack top : to get the top value in the stack
int stackTop(struct Stack st){
if(st.top == -1){
return 0;
}else {
return st.s[st.top];
}
}
// Time complexity : O(1)
void push(struct Stack *st ,int value){
if(!isFull(st)){
st->top++;
st->s[st->top] = value;
}else {
printf("\nStack is full.");
}
}
// Time complexity : O(1)
int pop(struct Stack *st ){
int value = -1;
if(!isEmpty(st)){
value = st->s[st->top];
st->top--;
printf("\nThe %d value is deleted from the stack." , value);
}else{
printf("\nStack is empty!");
}
return value;
}
// knowing the value by position
// time complexity : O(1);
int peak(struct Stack st , int pos){
int x = -1;
if(pos < st.top-pos +1){
printf("Invalid Position!");
}else{
x = st.s[st.top-pos+1];
}
return x;
}
void display(struct Stack *st){
for(int i=0 ; i<=st->top ; i++){
printf("\n Element : %d" , st->s[i]);
}
}
int main()
{
struct Stack st;
printf("Enter the size of the array : ");
scanf("%d" , &st.size);
st.s = (int*)malloc(st.size * sizeof(int));
st.top = -1;
// insert values to the stack
push(&st , 10);
push(&st , 20);
push(&st , 30);
// traverse stack
display(&st);
// Delete value from the stack;
// pop(&st);
// traverse stack;
display(&st);
// int value = peak(st , 4);
// if(value !=-1){
// printf("The value is %d" , value);
// }else{
// printf("Invalid");
// }
int value = stackTop(st);
if(value){
printf("\nTop value is : %d" , value);
}else{
printf("\nThere is no top element in the stack.");
}
return 0;
}