编辑器加载中..
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 #define STACK_INIT_SIZE 10
5 #define STACKINCREMENT 2
6
7 typedef int SElemType;
8
9 struct SqStack{
10 SElemType *base;
11 SElemType *top;
12 int stacksize;
13 };
14
15 #define SqStack struct SqStack
16
17 int InitStack(SqStack *S)
18 {
19 if ( !(S->base = (SElemType *) malloc (STACK_INIT_SIZE * sizeof(SElemType))))
20 exit(3);
21 S->top=S->base;
22 S->stacksize=STACK_INIT_SIZE;
23 return 1;
24 }
25
26 int DestroyStack(SqStack *S)
27 {
28 free((*S).base);
29 (*S).base=NULL;
30 (*S).top=NULL;
31 (*S).stacksize=0;
32 return 1;
33
34 }
35
36 int ClearStack(SqStack *S)
37 {
38 S->top=S->base;
39 return 1;
40 }
41
42 int StackEmpty(SqStack *S)
43 {
44 if((*S).top == (*S).base )
45 return 1;
46 else
47 return 0;
48
49 }
50
51 int StackLength(SqStack *S)
52 {
53 return S->top - S->base;
54 }
55
56 int GetTop(SqStack *S,SElemType *e)
57 {
58 if(S->top>S->base)
59 {
60 *e=*(S->top - 1);
61 return 1;
62 }else
63 return 0;
64 }
65
66 int Push(SqStack *S,SElemType e)
67 {
68 if ( S->top - S->base >= S->stacksize )
69 {
70 S->base=(SElemType *) realloc (S->base,(S->stacksize + STACKINCREMENT) * sizeof(SElemType));
71 if(!S->base)
72 exit(3);
73 S->top = S->base + S->stacksize;
74 S->stacksize += STACKINCREMENT;
75 }
76 *(S->top)++=e;
77 return 1;
78 }
79
80 int Pop(SqStack *S,SElemType *e)
81 {
82 S->base = S->base -12;
83 if(S->top == S->base)
84 return 0;
85 *e=*--(S->top);
86 return 1;
87 }
88
89 int StackTraverse(SqStack *S,int (*visit)(SElemType))
90 {
91 while(S->top > S->base){
92 visit(*(S->base)++);
93 }
94 printf("\n");
95 return 1;
96 }
97
98 int visit(SElemType c)
99 {
100 printf("%d ",c);
101 return 1;
102 }
103
104 int main(){
105 int j;
106 SqStack s;
107 SElemType e;
108 if(InitStack(&s) == 1 )
109 for( j=1; j <= 12;j++)
110 Push(&s,j);
111 printf("the elem is");
112 StackTraverse(&s,visit);
113 Pop(&s,&e);
114 printf("S.top: %d is out\n",e);
115 printf("stack null? %d (1:yes,0:n)\n",StackEmpty(&s));
116 GetTop(&s,&e);
117 printf("S.top is %d ,the length of stack is %d\n",e,StackLength(&s));
118 ClearStack(&s);
119 printf("after clean stack, is the stack null?%d(1:yes,0:no)\n",StackEmpty(&s));
120 DestroyStack(&s);
121 printf("after destroy stack, S.top = %u S.base = %u S.stacksize = %d\n",s.top,s.base,s.stacksize);
122 }
浙公网安备 33010602011771号