1 #include<string.h>
2 #include<ctype.h>
3 #include<malloc.h>
4 #include<limits.h>
5 #include<stdio.h>
6 #include<stdlib.h>
7 #include<math.h>
8
9 #define TRUE 1
10 #define FALSE 0
11 #define OK 1
12 #define ERROR 0
13 #define INFEASIBLE -1
14
15 typedef int Status;
16 typedef int Boolean;
17 typedef int SElemType;
18
19 #define STACK_INIT_SIZE 10
20 #define STACKINCREMENT 2
21 typedef struct SqStack{
22 SElemType *base;
23 SElemType *top;
24 int stacksize;
25 }SqStack;
26
27
28
29 Status InitStack(SqStack *S){
30 //构造一个空栈S
31 (*S).base=(SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType));
32 if(!(*S).base)
33 exit(OVERFLOW);
34 (*S).top=(*S).base;
35 (*S).stacksize=STACK_INIT_SIZE;
36 return OK;
37 }
38
39 Status DestroyStack(SqStack *S){
40 //销毁栈S,S不再存在
41 free((*S).base);
42 (*S).base=NULL;
43 (*S).top=NULL;
44 (*S).stacksize=0;
45 return OK;
46 }
47
48
49 Status ClearStack(SqStack *S){
50 //把S置为空栈
51 (*S).top=(*S).base;
52 return OK;
53 }
54
55 Status StackEmpty(SqStack S){
56 //若栈S为空栈,则返回TRUE,否则返回FALSE
57 if(S.top==S.base)
58 return TRUE;
59 else
60 return FALSE;
61 }
62
63
64 int StackLength(SqStack S){
65 //返回栈中元素的个数,及即栈的长度
66 return S.top-S.base;
67 }
68
69 Status GetTop(SqStack S,SElemType *e){
70 //若栈不空,则用e返回栈顶预案素,并返回OK ,否则返回ERROR
71 if(S.top>S.base){
72 *e=*(S.top-1);
73 return OK;
74 }
75 else
76 return ERROR;
77 }
78
79 Status Push(SqStack *S,SElemType e){
80 //插入元素e为新的栈顶元素
81 if((*S).top-(*S).base>=(*S).stacksize){
82 (*S).base=(SElemType *)realloc((*S).base,((*S).stacksize+STACKINCREMENT)*sizeof(SElemType));
83 if(!(*S).base)
84 exit(OVERFLOW);
85 (*S).top=(*S).base+(*S).stacksize;
86 (*S).stacksize+=STACKINCREMENT;
87 }
88 *((*S).top)++=e;
89 return OK;
90 }
91
92 Status Pop(SqStack *S,SElemType *e){
93 //若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERROR;
94 if((*S).top==(*S).base)
95 return ERROR;
96 *e=*--(*S).top;
97 return OK;
98 }
99
100 Status StackTraverse(SqStack S,Status (*visit)(SElemType)){
101 //从栈底到栈顶一次对栈中的每个元素调用函数visit().一旦visit()失败,则操作失败
102 while(S.top>S.base)
103 visit(*S.base++);
104 printf("\n");
105 return OK;
106 }