-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharraystack-full.c
More file actions
69 lines (58 loc) · 1.24 KB
/
arraystack-full.c
File metadata and controls
69 lines (58 loc) · 1.24 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
#include <stdio.h>
#define MAX 5
int stack_arr[MAX];
int top = -1;
// 1. Helper function to check if full
int isFull() {
if (top == MAX - 1) return 1;
return 0;
}
// 2. Helper function to check if empty
int isEmpty() {
if (top == -1) return 1;
return 0;
}
// 3. PUSH: Uses isFull()
void push(int data) {
if (isFull()) {
printf("Stack Overflow!\n");
return;
}
stack_arr[++top] = data; // Pre-increment top and assign
}
// 4. POP: Uses isEmpty()
void pop() {
if (isEmpty()) {
printf("Stack Underflow!\n");
return;
}
printf("Popped: %d\n", stack_arr[top--]); // Print and post-decrement top
}
// 5. PEEK: Uses isEmpty()
void peek() {
if (isEmpty()) {
printf("Stack is empty.\n");
return;
}
printf("Top element: %d\n", stack_arr[top]);
}
// 6. DISPLAY: Uses isEmpty()
void display() {
if (isEmpty()) {
printf("Stack is empty.\n");
return;
}
printf("Stack elements: ");
for (int i = top; i >= 0; i--) {
printf("%d ", stack_arr[i]);
}
printf("\n");
}
int main() {
push(10);
push(20);
display(); // Prints: 20 10
pop(); // Pops 20
peek(); // Top is 10
return 0;
}