-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.c
85 lines (75 loc) · 1.53 KB
/
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <stdio.h>
#include <malloc.h>
#include <stdbool.h>
typedef struct node {
int value;
struct node *next;
} Node;
typedef struct {
int size;
Node *bottom, *top;
} Stack;
bool push(Stack *stack, int value) {
Node *new = (Node*) malloc(sizeof(Node));
new-> value = value;
new-> next = NULL;
if (stack-> bottom == NULL) {
stack-> bottom = new;
stack-> top = new;
new-> next = NULL;
} else {
stack-> top-> next = new;
stack-> top = new;
new-> next = NULL;
}
stack-> size++;
return true;
}
bool pop(Stack *stack) {
if (stack == NULL) return false;
Node *prev = NULL;
Node *bottom = stack-> bottom;
while (bottom-> next != NULL) {
prev = bottom;
bottom = bottom-> next;
}
prev-> next = NULL;
stack-> top = prev;
free(bottom);
stack-> size--;
return true;
}
void size(Stack *stack) {
printf("Size of the stack: %i\n", stack-> size);
}
void display(Node *bottom) {
if (bottom == NULL) return; // base case
display(bottom-> next);
printf("|%i|\n", bottom-> value);
}
void peek(Stack *stack) {
if (stack-> bottom == NULL) {
printf("The stack is empty\n");
return;
} else {
printf("Last element on stack: %i\n", stack-> top-> value);
}
}
int main () {
Stack stack;
stack.bottom = NULL;
stack.top = NULL;
stack.size = 0;
push(&stack, 2);
push(&stack, 3);
push(&stack, 4);
push(&stack, 5);
display(stack.bottom);
size(&stack);
pop(&stack);
printf("\n");
display(stack.bottom);
size(&stack);
peek(&stack);
return 0;
}