1 /*
2 * 三、数据结构基础之顺序栈
3 * 顺序栈数据结构(结构的定义+在此结构上的操作)
4 * --- 2012年4月23日 ---by lee
5 */
6
7 #ifndef _SEQUENTIAL_STACK_H
8 #define _SEQUENTIAL_STACK_H
9
10 #include "Utility.h"
11
12 //宏定义栈的空间大小
13 #define STACKSIZE 20
14
15 //类型定义
16 typedef int DataType;
17
18 //声明顺序栈类型结构体
19 typedef struct _SqStack
20 {
21 DataType data[STACKSIZE];//存放数据元素的数组
22 int top;//指向栈顶位置
23 } SqStack;
24
25 //对顺序栈的基本操作
26
27 void InitStack(SqStack* stack);//初始化,构造空栈
28 int IsStackEmpty(SqStack* stack);//判断栈是否为空
29 int IsStackFull(SqStack* stack);//判断栈是否为满
30 void Push(SqStack* stack, DataType x);//元素x入栈
31 DataType Pop(SqStack* stack);//栈顶出栈,返回栈顶元素
32 DataType StackTop(SqStack* stack);//取栈顶元素
33
34 //初始化,构造空栈
35 void InitStack(SqStack* stack)
36 {
37 stack->top=-1;
38 }
39
40 //判断栈是否为空
41 int IsStackEmpty(SqStack* stack)
42 {
43 return (stack->top==-1);
44 }
45
46 //判断栈是否为满
47 int IsStackFull(SqStack* stack)
48 {
49 return (stack->top==STACKSIZE-1);
50 }
51
52 //元素x入栈
53 void Push(SqStack* stack, DataType x)
54 {
55 //首先判断栈是否已满
56 if(IsStackFull(stack))
57 Error("Stack is full");
58 //栈顶指针加1
59 ++stack->top;
60 stack->data[stack->top]=x;
61 }
62
63 //出栈,返回栈顶元素
64 DataType Pop(SqStack* stack)
65 {
66 //出栈前,判断栈是否为空
67 if(IsStackEmpty(stack))
68 Error("Stack is empty");
69 //保存栈顶元素
70 DataType ret=stack->data[stack->top];
71 stack->top--;//栈顶指针减1
72 return ret;
73 }
74
75 //取栈顶元素
76 DataType StackTop(SqStack* stack)
77 {
78 if(IsStackEmpty(stack))
79 Error("Stack is empty");
80
81 return stack->data[stack->top];
82 }
83
84 #endif
85
86 //测试代码
87 /*
88 SqStack s;
89 InitStack(&s);
90 Push(&s,1);
91 Push(&s,2);
92 Push(&s,3);
93 printf("stack top: %d\n",Pop(&s));
94 printf("stack top: %d\n",Pop(&s));
95 */