forked from seeditsolution/cprogram
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack_implementation.c
125 lines (119 loc) · 2.24 KB
/
stack_implementation.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
//Stack implementation using static array
#include<stdio.h>
#define CAPACITY 5 //Pre-processor macro and change the size if you want
int stack[CAPACITY], top=-1 ;
void push(int);
int pop(void);
int isFull(void);
int isEmpty(void);
void traverse(void);
void peek(void);
void main()
{
char ch;
long int item;
while(1)
{
printf("\n ---------------------- \n 1.Push an element \n 2.PoP element\n 3.Peek \n 4.Traverse\n 5.Quit \n ---------------------- \n");
printf("Enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\nEnter element to push:");
scanf("%d",&item);
push(item);
break;
case 2: item = pop();
if(item==0)
{
printf("Stack is underflow\n");
}
else
{
printf("Popped item: %d\n",item);
}
break;
case 3: peek();
break;
case 4: traverse();
break;
case 5: exit(0);
default: printf("Invalid input\n\n");
break;
}
}
}
int isFull()
{
if(top== CAPACITY-1)
{
return 1;
}
else
{
return 0;
}
}
int isEmpty()
{
if(top==-1)
{
return 1;
}
else
{
return 0;
}
}
void push(int ele)
{
if(isFull())
{
printf("\n Stack is overflow...\n");
}
else
{
top++;
stack[top] = ele;
printf("\n %d pushed into stack \n", ele);
}
}
int pop()
{
if(isEmpty())
{
return 0;
}
else
{
return stack[top--];
}
}
void peek()
{
if(isEmpty())
{
printf("\nStack is empty \n");
}
else
{
printf("\n Peek element: %d \n",stack[top]);
}
}
void traverse()
{
if(isEmpty())
{
printf("\n Stack is empty \n");
}
else
{
int i;
printf("\n Stack elements : \n");
for(i=0;i<=top;i++)
{
printf("%d\n________________ \n",stack[i]);
}
}
}