-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.c
More file actions
61 lines (53 loc) · 1.03 KB
/
Copy pathstack.c
File metadata and controls
61 lines (53 loc) · 1.03 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
#include <stdio.h>
#define MAX_SIZE 100
typedef struct {
int items[MAX_SIZE];
int top;
} Stack;
// Initialize
void initStack(Stack *s) {
s->top = -1;
}
// Check if empty
int isEmpty(Stack *s) {
return s->top == -1;
}
// Check if full
int isFull(Stack *s) {
return s->top == MAX_SIZE - 1;
}
// Push
void push(Stack *s, int value) {
if (isFull(s)) {
printf("Stack overflow!\n");
return;
}
s->items[++(s->top)] = value;
}
// Pop
int pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack underflow!\n");
return -1;
}
return s->items[(s->top)--];
}
// Peek (top element without removing)
int peek(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty!\n");
return -1;
}
return s->items[s->top];
}
// Display
void displayStack(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty.\n");
return;
}
printf("Stack (top -> bottom): ");
for (int i = s->top; i >= 0; i--)
printf("%d ", s->items[i]);
printf("\n");
}