-
Notifications
You must be signed in to change notification settings - Fork 0
/
stackusingarray.c
98 lines (82 loc) · 2.31 KB
/
stackusingarray.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
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 5
struct Stack {
int top;
int array[MAX_SIZE];
};
// Function to initialize the stack
void initializeStack(struct Stack *stack) {
stack->top = -1;
}
// Function to check if the stack is empty
int isEmpty(struct Stack *stack) {
return (stack->top == -1);
}
// Function to check if the stack is full
int isFull(struct Stack *stack) {
return (stack->top == MAX_SIZE - 1);
}
// Function to push an element onto the stack
void push(struct Stack *stack, int data) {
if (isFull(stack)) {
printf("Stack Overflow. Cannot push %d\n", data);
return;
}
stack->array[++stack->top] = data;
printf("%d pushed onto the stack\n", data);
}
// Function to pop an element from the stack
int pop(struct Stack *stack) {
if (isEmpty(stack)) {
printf("Stack Underflow. Cannot pop\n");
return -1;
}
int data = stack->array[stack->top--];
printf("%d popped from the stack\n", data);
return data;
}
// Function to display the elements of the stack
void displayStack(struct Stack *stack) {
if (isEmpty(stack)) {
printf("Stack is empty\n");
return;
}
printf("Elements in the stack: ");
for (int i = 0; i <= stack->top; i++)
printf("%d ", stack->array[i]);
printf("\n");
}
int main() {
struct Stack stack;
initializeStack(&stack);
int choice, data;
do {
printf("\n----- Stack Menu -----\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Display\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter the element to push: ");
scanf("%d", &data);
push(&stack, data);
break;
case 2:
pop(&stack);
break;
case 3:
displayStack(&stack);
break;
case 4:
printf("Exiting the program\n");
break;
default:
printf("Invalid choice. Please enter a valid option.\n");
}
} while (choice != 4);
return 0;
}