-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.h
102 lines (76 loc) · 1.35 KB
/
stack.h
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
92
93
94
95
96
97
98
99
100
101
102
#define ERROR_CHAR '?'
typedef struct node
{
char element;
struct node *next;
} node;
typedef struct stack
{
node *top;
} stack;
stack *create_stack()
{
stack *new_stack;
new_stack = malloc(sizeof(stack));
new_stack->top = NULL;
return new_stack;
}
node *create_node(char element)
{
node *new_node = malloc(sizeof(node));
new_node->next = NULL;
new_node->element = element;
return new_node;
}
void push(stack *st, char element)
{
node *new_node;
if (st == NULL)
return;
new_node = create_node(element);
new_node->next = st->top;
new_node->element = element;
st->top = new_node;
}
// Returns ERROR_CHAR if the stack is empty
char pop(stack *st)
{
char element;
node *new_top;
if (st == NULL)
return ERROR_CHAR;
if (st->top == NULL)
return ERROR_CHAR;
new_top = st->top->next;
element = st->top->element;
free(st->top);
st->top = new_top;
return element;
}
// Returns 1 if the stack is empty, returns 0 otherwise.
int is_empty(stack *st)
{
if (st == NULL || st->top == NULL)
return 1;
return 0;
}
char top(stack *st)
{
if (st == NULL || st->top == NULL)
return ERROR_CHAR;
return st->top->element;
}
void free_stack(stack *st)
{
node *cur_node, *last_node;
if (st == NULL)
return;
cur_node = st->top;
while (cur_node != NULL)
{
last_node = cur_node;
cur_node = cur_node->next;
free(last_node);
}
free(st);
}