-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stack Implementation.c
64 lines (51 loc) · 1.1 KB
/
Stack Implementation.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
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
struct Stack {
int items[MAX_SIZE];
int top;
};
void initStack(struct Stack* stack) {
stack->top = -1;
}
int isEmpty(struct Stack* stack) {
return stack->top == -1;
}
int isFull(struct Stack* stack) {
return stack->top == MAX_SIZE - 1;
}
void push(struct Stack* stack, int value) {
if (isFull(stack)) {
printf("Stack overflow\n");
return;
}
stack->top++;
stack->items[stack->top] = value;
}
int pop(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack underflow\n");
exit(1);
}
return stack->items[stack->top--];
}
int peek(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty\n");
exit(1);
}
return stack->items[stack->top];
}
int main() {
struct Stack stack;
initStack(&stack);
push(&stack, 1);
push(&stack, 2);
push(&stack, 3);
printf("Top element: %d\n", peek(&stack));
printf("Elements: ");
while (!isEmpty(&stack))
printf("%d ", pop(&stack));
printf("\n");
return 0;
}