顺序栈的C代码实现

  1 /*
2 顺序栈的练习
3
4 栈的抽象数据类型:
5 ADT 栈(Stack)
6 Data:
7 元素具有相同的数据类型,相邻元素之间有前驱和后继的关系。
8 Operation:
9 InitStack(*S);
10 DestroyStack(*S);
11 IsEmpty(*S);
12 ClearStack(*S);
13 GetTop(*S, *e);
14 Push(*S, e);
15 Pop(*S, e);
16 StackLength(*S);
17 EndADT
18 */
19
20 #include<stdio.h>
21 #include<stdlib.h>
22 #define MAXSIZE 5
23 #define TRUE 1
24 #define FALSE 0
25 #define OK 1
26 #define ERROR 0
27
28 typedef int Status;
29 typedef int ElemType;
30 typedef struct
31 {
32 ElemType data[MAXSIZE];
33 int top;
34 }SqStack;
35
36 /*
37 功能:初始化一个栈
38 */
39 void InitStack(SqStack *s)
40 {
41 s->top = -1;
42 }
 43 /*
44 功能:判断栈是否为空,如果为空,返回true
45 */
46 Status IsEmpty(SqStack *S)
47 {
48 if(S->top == -1)
49 return TRUE;
50 return FALSE;
51 }
52
53 /*
54 功能:将栈清空
55 */
56 void ClearStack(SqStack *s)
57 {
58 s->top = -1;
59 }
60
61 /*
62 功能:将数据 e 压入栈
63 */
64 Status Push(SqStack *S, ElemType e)
65 {
66 if(S->top == MAXSIZE-1)
67 return ERROR;
68 S->top++;
69 S->data[S->top] = e;
70 return OK;
71 }
72 /*
73 功能:若栈不空,则删除栈顶元素,并把元素值赋给 e
74 */
75 Status Pop(SqStack *S, ElemType *e)
76 {
77 if(S->top == -1)
78 return ERROR;
79 *e = S->data[S->top];
80 S->top--;
81 return OK;
82 }
83 /*
84 功能:取得栈的长度
85 */
86 Status StackLength(SqStack *s)
87 {
88 return s->top+1;
89 }
90
91 /*
92 功能:获得栈顶的元素值,并将其赋值给 e
93 */
94 Status GetTop(SqStack *s, ElemType *e)
95 {
96 if(s->top == -1)
97 return ERROR;
98 *e = s->data[s->top];
99 return OK;
100 }
101
102 /*
103 功能: main方法中为测试数据
104 */
105
106 int main()
107 {
108 SqStack s;
109 InitStack(&s);
110 printf("%d\n", s.top);
111
112 ElemType a = 100;
113 Push(&s, a);
114 a = 333;
115 Push(&s, a);
116 a = 45;
117 Push(&s, a);
118 printf("len = %d\n", StackLength(&s));
119
120 printf("data =\t");
121 for(int i=0; i<StackLength(&s); i++)
122 printf("%d\t", s.data[i]);
123 printf("\n");
124
125 ElemType b;
126 Pop(&s, &b);
127 printf("b = %d\n", b);
128 printf("len = %d\n", StackLength(&s));
129
130 GetTop(&s, &b);
131 printf("b = %d\n", b);
132
133 printf("%d\n", IsEmpty(&s));
134
135 ClearStack(&s);
136 printf("top = %d\n", s.top);
137 printf("len = %d\n", StackLength(&s));
138
139 DestroyStack(&s);
140 Push(&s, a);
141 Push(&s, a);
142 printf("top = %d\n", s.top);
143 system("pause");
144 return 0;
145 }

 

【Stay hungry, Stay foolish】

  ^_^  Eric

posted @ 2012-02-25 00:43  eric.dream  阅读(1064)  评论(0编辑  收藏  举报