-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.c
143 lines (120 loc) · 2.26 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
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
/**
*
* PUSH, POP and TOS operations of Stack
*/
#include<stdio.h>
#include<stdlib.h>
#define MAX_SIZE 10
struct Stack
{
int array[MAX_SIZE];
int top;
};
int SIZE;
/**
* Initialize stack
*
* @param stackPointer
*/
void initialize(struct Stack *stackPointer) {
stackPointer->top = -1;
}
/**
* Check if stack is empty
*
* @param stackPointer
*/
int isEmpty(struct Stack *stackPointer) {
if(stackPointer->top == -1)
return 1;
return 0;
}
/**
* Check if stack is full
*
* @param stackPointer
*/
int isFull(struct Stack *stackPointer) {
if(stackPointer->top == SIZE - 1)
return 1;
return 0;
}
/**
* Push an item into top of the stack
*
* @param stackPointer
* @param item
*/
void push(struct Stack *stackPointer, int item) {
if(isFull(stackPointer)) {
printf("\n Sorry, stack is full. \n");
} else {
stackPointer->top++;
stackPointer->array[stackPointer->top] = item;
}
}
/**
* Pop an item from top of the stack
*
* @param stackPointer
* @returns
*/
void pop(struct Stack *stackPointer) {
int item;
if(isEmpty(stackPointer)) {
printf("\n Sorry, stack is empty. \n");
} else {
item = stackPointer->array[stackPointer->top];
stackPointer->top--;
printf("\n %d successfully popped from stack. \n", item);
}
}
/**
* Display an item at top of the stack
*
* @param stackPointer
*/
void tos(struct Stack *stackPointer) {
int item;
if(isEmpty(stackPointer)) {
printf("\n Sorry, stack is empty. \n");
} else {
item = stackPointer->array[stackPointer->top];
printf("\n %d is at top of the stack. \n", item);
}
}
/**
* Main function
*/
int main() {
char choice;
int item;
struct Stack stack;
initialize(&stack);
printf("\n Enter size of the stack: ");
scanf("%d", &SIZE);
while(choice != '4') {
printf("\n 1. PUSH \n 2. POP \n 3. TOS \n 4. EXIT \n");
printf("\n Enter your choice (1, 2, 3 or 4): ");
scanf(" %c", &choice);
switch (choice)
{
case '1':
printf("\n Enter an item to push into stack: ");
scanf("%d", &item);
push(&stack, item);
break;
case '2':
pop(&stack);
break;
case '3':
tos(&stack);
break;
case '4':
exit(0);
default:
break;
}
}
return 0;
}