-
Notifications
You must be signed in to change notification settings - Fork 1
/
stack.c
72 lines (67 loc) · 1.16 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
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
typedef struct node {
int pc;
struct node *prev;
struct node *next;
} node;
extern void free_resources(void);
node *stack = NULL;
void stack_push(node *new_node)
{
if (!stack) {
stack = new_node;
new_node->next = stack;
new_node->prev = stack;
} else {
new_node->next = stack;
new_node->prev = stack->prev;
stack->prev->next = new_node;
stack->prev = new_node;
stack = new_node;
}
}
node *stack_pop(void) {
node *tmp;
if (!stack) {
return NULL;
}
if (stack->next == stack) {
tmp = stack;
stack = NULL;
return tmp;
} else {
stack->next->prev = stack->prev;
stack->prev->next = stack->next;
tmp = stack;
stack = stack->next;
return tmp;
}
}
void push_address(int PC)
{
node *new_node = malloc(sizeof(node));
if (!new_node) {
printf("malloc call func error!\n");
free_resources();
exit(-1);
}
memset(new_node, 0, sizeof(node));
new_node->pc = PC;
stack_push(new_node);
}
int pop_address(void)
{
int PC;
node *node = stack_pop();
if (!node) {
printf("stack empty!\n");
free_resources();
exit(-1);
}
PC = node->pc;
free(node);
return PC;
}