1 #include "stdio.h"
2 #include "stdlib.h"
3 #include "io.h"
4 #include "math.h"
5 #include "time.h"
6
7 #define OK 1
8 #define ERROR 0
9 #define TRUE 1
10 #define FALSE 0
11 #define MAXSIZE 20 /* 存储空间初始分配量 */
12
13 typedef int Status;
14 typedef int SElemType; /* SElemType类型根据实际情况而定,这里假设为int */
15
16 /* 顺序栈结构 */
17 typedef struct
18 {
19 SElemType data[MAXSIZE];
20 int top; /* 用于栈顶指针 */
21 }SqStack;
22
23 Status visit(SElemType c){
24 printf("%d\n",c);
25 return OK;
26 }
27
28 /* 构造一个空栈S */
29 Status InitStack(SqStack *S){
30 S->top = -1;
31 return OK;
32 }
33
34 /* 把S置为空栈 */
35 Status ClearStack(SqStack *S){
36 S->top = -1;
37 return OK;
38 }
39
40 /* 若栈S为空栈,则返回TRUE,否则返回FALSE */
41 Status StackEmpty(SqStack S){
42 if(S.top == -1){
43 return TRUE;
44 }else{
45 return FALSE;
46 }
47 }
48
49 /* 返回S的元素个数,即栈的长度 */
50 int StackLength(SqStack S){
51 return S.top+1;
52 }
53
54 /* 若栈不空,则用e返回S的栈顶元素,并返回OK;否则返回ERROR */
55 Status GetTop(SqStack S,SElemType *e){
56 if(S.top == -1) return ERROR;
57 *e = S.data[S.top];
58 return OK;
59 }
60
61 /* 插入元素e为新的栈顶元素 */
62 Status Push(SqStack *S,SElemType e){
63 if(S->top+1==MAXSIZE) return ERROR;
64 S->data[++S->top] = e;
65 return OK;
66 }
67
68 /* 若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERROR */
69 Status Pop(SqStack *S,SElemType *e){
70 if(S->top == -1) return ERROR;
71 *e = S->data[S->top--];
72 return OK;
73 }
74
75 /* 从栈底到栈顶依次对栈中每个元素显示 */
76 Status StackTraverse(SqStack S){
77 if(S.top == -1) return ERROR;
78 int i;
79 for(i=0;i<=S.top;i++){
80 visit(S.data[i]);
81 }
82 printf("\n");
83 return OK;
84 }
85
86 int main(void){
87 int j;
88 SqStack s;
89 int e;
90 if(InitStack(&s)==OK)
91 for(j=1;j<=10;j++)
92 Push(&s,j);
93 printf("栈中元素依次为:");
94 StackTraverse(s);
95 Pop(&s,&e);
96 printf("弹出的栈顶元素 e=%d\n",e);
97 printf("栈空否:%d(1:空 0:否)\n",StackEmpty(s));
98 GetTop(s,&e);
99 printf("栈顶元素 e=%d 栈的长度为%d\n",e,StackLength(s));
100 ClearStack(&s);
101 printf("清空栈后,栈空否:%d(1:空 0:否)\n",StackEmpty(s));
102 return 0;
103 }