栈
栈的顺序存储结构
顺序栈的实现
栈的顺序存储类型可描述为:
|  | #define MaxSize 50				typedef struct{
 ElemType data[MaxSize];
 int top;
 }SqStack;
 
 | 
顺序栈的基本运算
初始化
|  | void InitStack(SqStack &s){s.top=-1;
 }
 
 | 
判栈空
|  | bool StackEmpty(SqStack S){if(s.top == -1)
 return true;
 else
 return false;
 }
 
 | 
进栈
|  | bool Push(SqStack &s,ElemType x){if(s.top == MaxSize-1)
 return false;
 s.data[++s.top]=x;
 return true;
 }
 
 | 
出栈
|  | bool Pop(SqStack &s,ElemType &x){if(s.top == -1)
 return false;
 x=s.data[s.top--];
 return true;
 }
 
 | 
读栈顶元素
|  | bool GetTop(SqStack s,ElemType &x){
 if(s.top == -1 )
 return false;
 x=s.data[s.top];
 return true;
 }
 
 | 
顺序栈的完整操作
程序源代码:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 
 | #include<bits/stdc++.h>using namespace std;
 typedef int ElemType;
 #define MaxSize 50
 typedef struct{
 ElemType data[MaxSize];
 int top;
 }SqStack;
 void InitStack(SqStack &s){
 s.top=-1;
 }
 bool StackEmpty(SqStack S){
 if(S.top == -1)
 return true;
 else
 return false;
 }
 bool Push(SqStack &s,ElemType x){
 if(s.top == MaxSize-1)
 return false;
 s.data[++s.top]=x;
 return true;
 }
 bool Pop(SqStack &s,ElemType &x){
 if(s.top == -1)
 return false;
 x=s.data[s.top--];
 return true;
 }
 bool GetTop(SqStack s,ElemType &x)
 {
 if(s.top == -1 )
 return false;
 x=s.data[s.top];
 return true;
 }
 void PrintSqStack(SqStack s)
 {
 int tmp = s.top;
 while(tmp!=-1)
 {
 cout<<s.data[tmp--]<<" ";
 }
 cout<<endl;
 }
 int main()
 {
 SqStack s;
 InitStack(s);
 for(int i=1;i<=5;i++)
 {
 Push(s,i);
 }
 PrintSqStack(s);
 for(int i=1;i<=5;i++){
 int x;
 GetTop(s,x);
 cout<<"这是GetTop操作,栈顶元素为"<<x<<endl;
 cout<<"这是GetTop操作后的栈遍历:";
 PrintSqStack(s);
 Pop(s,x);
 cout<<"这是Pop操作,出栈的元素为"<<x<<endl;
 if(!StackEmpty(s))
 {
 cout<<"这是Pop操作后的栈遍历:";
 PrintSqStack(s);
 }else{
 cout<<"此时栈空!"<<endl;
 }
 
 }
 return 0;
 }
 
 | 
程序输出:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 
 | 5 4 3 2 1这是GetTop操作,栈顶元素为5
 这是GetTop操作后的栈遍历:5 4 3 2 1
 这是Pop操作,出栈的元素为5
 这是Pop操作后的栈遍历:4 3 2 1
 这是GetTop操作,栈顶元素为4
 这是GetTop操作后的栈遍历:4 3 2 1
 这是Pop操作,出栈的元素为4
 这是Pop操作后的栈遍历:3 2 1
 这是GetTop操作,栈顶元素为3
 这是GetTop操作后的栈遍历:3 2 1
 这是Pop操作,出栈的元素为3
 这是Pop操作后的栈遍历:2 1
 这是GetTop操作,栈顶元素为2
 这是GetTop操作后的栈遍历:2 1
 这是Pop操作,出栈的元素为2
 这是Pop操作后的栈遍历:1
 这是GetTop操作,栈顶元素为1
 这是GetTop操作后的栈遍历:1
 这是Pop操作,出栈的元素为1
 此时栈空!
 
 | 
栈的链式存储结构
栈的链式存储类型可描述为
|  | typedef struct Linknode{ElemType data;
 struct Linknode *next;
 }*Linknode;
 
 |