forked from matthewsamuel95/ACM-ICPC-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack_using_array.c
115 lines (104 loc) · 1.81 KB
/
stack_using_array.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
#include <stdio.h>
#include <stdlib.h>
#define MAX 500
struct Stack
{
int top;
int* a;
};
typedef struct Stack stack;
stack* createStack()
{
stack *s = malloc(sizeof(stack));
s->top = -1;
s->a = malloc(MAX * sizeof(int));
}
int isEmpty(stack* s)
{
if (s->top == -1)
{
return 1;
}
else
{
return 0;
}
}
int isFull(stack *s)
{
if (s->top == MAX-1)
{
return 1;
}
else
{
return 0;
}
}
void push(stack *s, int n)
{
if (isFull(s))
{
printf("Stack overflow\n");
}
else
{
s->a[++s->top] = n;
printf("%d pushed to stack\n", n);
}
}
void pop (stack *s)
{
if (isEmpty(s))
{
printf("Underflow\n");
}
else
{
printf("%d popped from the stack", s->a[s->top]);
s->top--;
}
}
int peek(stack *s)
{
if (isEmpty(s))
{
printf("Stack is empty\n");
}
else
{
return s->a[s->top];
}
}
void display(stack* s)
{
int i = 0;
for (i = s->top; i >= 0; i--)
{
printf("%d\t", s->a[i]);
}
printf("\n");
}
int main()
{
stack* s = createStack();
int c = 0;
printf("Enter 1 to push elements to stack.\nEnter 2 to pop elements from the stack.\nEnter 3 to peek topmost element in stack.\nEnter 4 to display content of the stack.\n");
scanf("%d", &c);
do
{
switch (c)
{
case 1: printf ("Enter element to be pushed: ");
int n = 0;
scanf("%d", &n);
push(s, n); break;
case 2: pop(s); break;
case 3: printf("%d\n", peek(s)); break;
case 4: display(s); break;
default: printf("Invalid input");
}
scanf("%d", &c);
} while (c != -1);
return 0;
}