-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.c
More file actions
91 lines (84 loc) · 1.56 KB
/
Stack.c
File metadata and controls
91 lines (84 loc) · 1.56 KB
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
/******************************/
/* */
/* Stack.cpp */
/* 动态栈实现,用于符号表 */
/******************************/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"Lex.h"
#include"Stack.h"
void init_stack(Stack* stack, int initsize) //栈初始化
{
stack->base = (void**)malloc(sizeof(void**)*initsize);
if (!stack->base)
{
error("内存分配失败!");
}
else
{
stack->top = stack->base;
stack->stacksize = initsize;
}
}
void* push(Stack* stack, void* e, int size) //元素入栈
{
int newsize;
if (stack->top >= stack->base + stack->stacksize)
{
newsize = stack->stacksize * 2;
stack->base = (void**)realloc(stack->base, sizeof(void**)*newsize);
if (!stack->base)
{
return NULL;
}
stack->top = stack->base + stack->stacksize;
stack->stacksize = newsize;
}
*stack->top = (void**)malloc(size);
memcpy(*stack->top, e, size);
stack->top++;
return *(stack->top - 1);
}
void pop(Stack* stack) // 弹出栈顶
{
if (stack->top > stack->base)
free(*(--stack->top));
}
void * get_top(Stack* stack)
{
void** e;
if (stack->top > stack->base)
{
e = stack->top - 1;
return *e;
}
else
{
return NULL;
}
}
int is_empty(Stack* stack)
{
if (stack->base == stack->top)
{
return 1;
}
else
return 0;
}
void stack_destroy(Stack* stack) //栈销毁
{
void **e;
for (e = stack->base; e < stack->top; e++)
{
free(*e);
}
if (stack->base)
{
free(stack->base);
}
stack->base = NULL;
stack->top = NULL;
stack->stacksize = 0;
}