-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack1.c
96 lines (79 loc) · 1.98 KB
/
stack1.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
//stack using array
#include <stdio.h>
#include <stdlib.h>
#define MAX 5
// Function to push an element onto the stack
void push(int stack[], int *top, int value) {
if (*top == MAX - 1) {
printf("Stack Overflow\n");
} else {
(*top)++;
stack[*top] = value;
printf("%d pushed onto the stack\n", value);
}
}
// Function to pop an element from the stack
int pop(int stack[], int *top) {
if (*top == -1) {
printf("Stack Underflow\n");
return -1;
} else {
int value = stack[*top];
(*top)--;
return value;
}
}
// Function to display the elements of the stack
void display(int stack[], int top) {
if (top == -1) {
printf("Stack is empty\n");
} else {
printf("Stack elements are: ");
for (int i = top; i >= 0; i--) {
printf("%d ", stack[i]);
}
printf("\n");
}
}
void peek(int stack[],int top){
if(top==-1){
printf("stack empty");
}
else{
printf("%d",stack[top] );
top--;
}
}
int main() {
int stack[MAX], top= -1;
int choice, value;
while (1) {
printf("\n1. Push\n2. Pop\n3. Display\n 4. peek \n 5. Exit\nEnter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter value to push: ");
scanf("%d", &value);
push(stack, &top, value);
break;
case 2:
value = pop(stack, &top);
if (value != -1) {
printf("Popped element: %d\n", value);
}
break;
case 3:
display(stack, top);
break;
case 5:
exit(0);
case 4:
peek(stack,top);
break;
default:
printf("Invalid choice, please try again.\n");
break;
}
}
return 0;
}