forked from xiufengcheng/DATASTRUCTURE
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSqStack.h
More file actions
65 lines (55 loc) · 1.96 KB
/
SqStack.h
File metadata and controls
65 lines (55 loc) · 1.96 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
# define STACK_INIT_SIZE 100 // 顺序栈 (默认的)的初始分配最大容量
# define STACKINCREMENT 10 // (默认的)增补空间量
typedef struct {
ElemType *stack; // 存储数据元素的一维数组
int top; // 栈顶指针
int stacksize; // 当前分配的数组容量(以ElemType为单位)
int incrementsize; // 增补空间量(以ElemType为单位)
}SqStack;
void InitStack_Sq(SqStack &S, int maxsize=STACK_INIT_SIZE,
int incresize=STACKINCREMENT )
{
S.stack=(ElemType *)malloc(maxsize*sizeof(ElemType)); // 为顺序栈分配初始存储空间
if(!S.stack) exit(1); // 存储空间分配失败
S.top=-1; // 置栈空
S.stacksize=maxsize; // 顺序栈的当前容量
S.incrementsize=incresize; // 增补空间
}// InitStack_Sq
int StackLength_Sq(SqStack S)
{
return S.top+1;
}// StackLength_Sq
bool Push_Sq(SqStack &S,ElemType e)
{ //在顺序栈的栈顶插入元素e
if(S.top==S.stacksize-1) {
S.stack =(ElemType *)realloc(S.stack,(S.stacksize+S.
incrementsize)*sizeof(ElemType)); // 栈满,给顺序栈增补空间
if(!S.stack) return false; // 分配存储空间失败
S.stacksize+=S.incrementsize;
}
S.stack[++S.top]=e; // 栈顶指针上移,元素e进栈
return true;
}// Push_Sq
bool Pop_Sq(SqStack &S,ElemType &e)
{ // 删除顺序栈栈顶元素,并让e返回其值
if(S.top==-1) return false;
e=S.stack[S.top--];
return true;
}// Pop_Sq
bool GetTop_Sq(SqStack S, ElemType &e)
{ //取顺序栈栈顶元素,并让e返回其值
if(S.top==-1) return false;
e=S.stack[S.top];
return true;
}// GetTop_Sq
bool StackEmpty_Sq(SqStack S)
{ if(S.top==-1) return true;
else return false;
}// StackEmpty_Sq
void DestroyStack_Sq(SqStack &S )
{
free(S.stack);
S.stack=NULL;
S.stacksize=0;
S.top=-1;
}// DestroyStack_Sq