-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.c
More file actions
100 lines (79 loc) · 1.73 KB
/
stack.c
File metadata and controls
100 lines (79 loc) · 1.73 KB
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
//8
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int*stack;
int max;
int top;
}st;
void display(st*p){
if(p->top==-1){
printf("STACK EMPTY\n");
return;
}
printf("\nSTACK:\n");
for(int i=p->top;i>=0;i--){
printf("%d\n",p->stack[i]);
}
}
void push(st*p){
if(p->top==p->max-1){
printf("STACK OVERFLOW\n");
return;
}
int val;
printf("Enter the value to insert: ");
scanf("%d",&val);
p->stack[++p->top]=val;
}
void pop(st*p){
if(p->top==-1){
printf("STACK UNDERFLOW\n");
return;
}
printf("Popped value: %d\n",p->stack[p->top--]);
}
void peek(st*p){
if(p->top==-1){
printf("STACK EMPTY\n");
return;
}
printf("TOP OF STACK-> %d\n",p->stack[p->top]);
}
void main(){
st*p=(st*)malloc(sizeof(st));
if(p==NULL){
printf("Memory allocation failed...\n");
return;
}
p->top=-1;
printf("Enter the maximum capacity of the stack: ");
scanf("%d",&p->max);
p->stack=(int*)calloc(p->max,sizeof(int));
int ch;
for(;;){
printf("\nENTER:\n1. To display\n2. To push\n3. To pop\n4. To peek\n0. To EXIT\nEnter your choice from above: ");
scanf("%d",&ch);
switch(ch){
case 1:
display(p);
break;
case 2:
push(p);
break;
case 3:
pop(p);
break;
case 4:
peek(p);
break;
case 0:
printf("Exiting...\n");
free(p);
free(p->stack);
exit(0);
default:
printf("Invalid Choice! Please Enter Again!\n");
}
}
}