-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.c
91 lines (77 loc) · 1.7 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
86
87
88
89
90
91
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define true 1
#define false 0
# define STACK_SIZE 10
struct stack {
int elements[STACK_SIZE];
int top; // stack pointer
};
struct stack* initialize_stack();
int isFull(struct stack*);
int isEmpty(struct stack*);
void push(struct stack*, int);
int pop(struct stack*);
void print_stack(struct stack*);
int main() {
struct stack* my_stack = initialize_stack();
push(my_stack, 5);
push(my_stack, 10);
push(my_stack, 3);
print_stack(my_stack);
pop(my_stack);
print_stack(my_stack);
free(my_stack);
return 0;
}
/**
** creates a stack structure, initialize its top, and return it
*/
struct stack* initialize_stack(){
struct stack* s = malloc(sizeof(struct stack));
s->top = -1;
return s;
};
int isFull(struct stack* s) {
if (s->top + 1 == STACK_SIZE){
return true;
}
return false;
}
int isEmpty(struct stack* s) {
if (s->top == -1) {
return true;
}
return false;
}
int pop(struct stack* s) {
// check if the stack is empty
if (isEmpty(s)) {
printf("underflow\n");
return -INFINITY;
}
// decrement top and return the item that was pointed to by the top before decrementing
s->top--;
return s->elements[s->top + 1];
}
void push(struct stack* s, int e) {
// check if the stack is full
if (isFull(s)) {
printf("overflow\n");
return;
}
// increment top and assign the item it now points to
s->top++;
s->elements[s->top] = e;
}
void print_stack(struct stack* s) {
if (isEmpty(s)) {
printf("Empty stack\n");
return;
}
printf("stack content:\n");
for (int i = 0; i <= s->top; i++) {
printf("%d\n", s->elements[i]);
}
}