-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathStack.c
More file actions
120 lines (111 loc) · 2.75 KB
/
Stack.c
File metadata and controls
120 lines (111 loc) · 2.75 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#include<stdio.h>
//Pre-processor macro
#define stackCapacity 5
int stack[stackCapacity], top=-1;
void push(int);
int pop(void);
int isFull(void);
int isEmpty(void);
void traverse(void);
void atTop(void);
//Main function of the program
void main(void)
{
int choice, stackItem;
//Always true While loop for continue iteration
while(1){
//Instructions to the user
printf("Stack Operation n");
printf("Enter `1` for Push Operation n");
printf("Enter `2` for Pop Operation n");
printf("Enter `3` for atTop Operation n");
printf("Enter `4` for Traverse Operation n");
printf("Enter `5` for Quit Operation n");
printf("Enter your choice : ");
scanf("%d",&choice);
//Switch Case to do the user specified task
switch(choice){
case 1:
printf("Enter a integer value : ");
scanf("%d",&stackItem);
push(stackItem);
break;
case 2:
stackItem = pop();
if(stackItem == 0){
printf("Your stack is underflow");
}else{
printf("Last popped item : %dn", stackItem);
}
break;
case 3:
atTop();
break;
case 4:
traverse();
break;
case 5:
return;
break;
default: printf("Please enter correct choice : ");
}
}
}
//Push Function to insert element into the stack
void push(int stackElement)
{
if(isFull()){
printf("Stack is full.It can't be overflowed. n");
}else{
top++;
stack[top] = stackElement;
printf("%d has been pushed n", stackElement);
}
}
//Function to check, Is stack full?
int isFull(){
if(top == stackCapacity-1){
return 1;
}else{
return 0;
}
}
//Function to check, Is stack empty?
int isEmpty(){
if(top == -1){
return 1;
}else{
return 0;
}
}
//Function to pop last element of the stack
int pop(){
if(isEmpty()){
return 0;
}else{
return stack[top--];
}
}
//function to check, Which element on the top?
void atTop()
{
if(isEmpty())
{
printf("Your Stack is empty n");
}else{
printf("Element at top is : %d n", stack[top]);
}
}
//Function to display the all the characters elements of stack
void traverse(){
if(isEmpty())
{
printf("Your Stack is empty n");
}else{
int i;
printf("Stack Elements are : n");
for(i=0; i <= top; i++){
printf("%d n", stack[i]);
}
}
}