-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple_stack.c
61 lines (45 loc) · 1.04 KB
/
simple_stack.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
#include <stdio.h>
#define CAPACITY 20
int stack[CAPACITY];
int top = -1;
int stack_is_empty() {
return (top <= 0);
}
int stack_len() {
return (top + 1);
}
int stack_is_full() {
return (top + 1 >= CAPACITY);
}
int stack_peek() {
return stack[top];
}
void stack_push(int val) {
if (stack_len() >= CAPACITY) {
printf("Stack Overflow\n");
return;
}
stack[++top] = val;
}
void stack_pop() {
if (stack_is_empty()) {
printf("Stack Underflow\n");
return;
}
top--;
}
int main() {
// Test empty stack
printf("Is the stack empty? %s\n", stack_is_empty() ? "Yes" : "No");
// Test push and peek
stack_push(10);
stack_push(20);
stack_push(30);
printf("Top element: %d\n", stack_peek());
// Test pop
stack_pop();
printf("Popped element\n");
// Test stack length
printf("Stack length: %d\n", stack_len());
return 0;
}