数据结构——顺序栈及其操作

 1 #include<iostream>
 2 using namespace std;
 3 
 4 typedef int SElemType;
 5 typedef int Status;
 6 #define OK 1
 7 #define ERROR 0
 8 
 9 
10 #define MAXSIZE 100        //栈的最大空间
11 
12 
13 //顺序栈的存储结构
14 typedef struct SqStack
15 {
16     SElemType *base;    //栈底指针
17     SElemType *top;        //栈顶指针
18 }SqStack;
19 
20 
21 //初始化,构造一个空栈
22 Status InitStack(SqStack &S)    //构造一个空栈S
23 {
24     S.base = new SElemType[MAXSIZE];
25 
26     if (!S.base)        //空间分配失败
27         return ERROR;
28 
29     S.top = S.base;        //空栈
30     return OK;
31 }
32 
33 
34 //入栈
35 //插入元素e为新的栈顶元素
36 Status Push(SqStack &S, SElemType e)
37 {
38     if (S.top - S.base == MAXSIZE)        //栈满
39         return ERROR;
40         
41     *(S.top++) = e;        //先e入栈,然后再栈顶指针+1
42     //注意这里的优先级,等价于*S.top = e; S.top++;
43     return OK;
44 }
45 
46 
47 //出栈
48 //删除栈顶元素,用e返回其值
49 Status Pop(SqStack &S, SElemType &e)
50 {
51     if (S.top == S.base)        //栈空
52         return ERROR;
53 
54     e = *--S.top;        //栈顶指针减1,将栈顶元素赋值给e
55     return OK;
56 }
57 
58 
59 //取栈顶元素
60 SElemType GetTop(SqStack S)
61 {
62     if (S.top != S.base)    //栈非空
63         return *(S.top - 1);    //返回栈顶元素的值,栈顶指针不变
64     //注意用S.top - 1 而不是S.top--,因为这样就会改变栈顶指针
65 }
66 
67 
68 int main()
69 {
70     int n, x;
71     SqStack S;
72 
73     InitStack(S);    //初始化顺序栈S
74 
75     cout << "请输入顺序栈中的元素个数n:" << endl;
76     cin >> n;
77     cout << "请依次输入" << n << "个元素,依次入栈:" << endl;
78     while (n--)
79     {
80         cin >> x;
81         Push(S, x);
82     }
83     cout << "元素依次出栈:" << endl;
84     while (S.top != S.base)        //栈非空
85     {
86         cout << GetTop(S) << " ";
87         Pop(S, x);
88     }
89 
90     system("pause");
91     return 0;
92 }
原文地址:https://www.cnblogs.com/friend-A/p/9072922.html