-
Notifications
You must be signed in to change notification settings - Fork 127
/
Copy pathstack.c
72 lines (52 loc) · 1.07 KB
/
stack.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
#include <stdio.h>
#include <stdlib.h>
typedef struct Stack {
int top;
int maxSize;
int *array;
} Stack;
Stack createStack(int size) {
Stack s = {-1, size, (int*)malloc(size * sizeof(int))};
return s;
}
void destroyStack(Stack *s) {
free(s -> array);
}
int isEmpty(Stack *s) {
return !(s -> top > -1);
}
int isFull(Stack *s) {
return !(s -> top < s -> maxSize - 1);
}
void push(Stack *s, int ele) {
if(!isFull(s))
s -> array[++(s -> top)] = ele;
else
printf("Overflow!\n");
}
int pop(Stack *s) {
if(!isEmpty(s)) {
int ele = s -> array[(s -> top)--];
return ele;
}
printf("Underflow!\n");
}
void display(Stack *s) {
if(isEmpty(s)) {
printf("Stack is Empty!\n");
return;
}
printf("top -> ");
for(int i = s -> top; i >= 0; --i)
printf("%d ", s -> array[i]);
printf("\n");
}
int main() {
Stack s1 = createStack(3);
push(&s1, 10); push(&s1, 30); push(&s1, 20);
display(&s1);
printf("Popped: %d\n", pop(&s1)); printf("Popped: %d\n", pop(&s1));
printf("Popped: %d\n", pop(&s1)); printf("Popped: %d\n", pop(&s1));
display(&s1);
destroyStack(&s1);
}