堆栈的顺序存储实现


 1 #include<iostream>
 2 #include<cstdlib>
 3 #include<cstdio>
 4 #define Max 50
 5 #define OK 1
 6 using namespace std;
 7 typedef int ElemType;
 8 typedef struct Stack //顺序栈的定义
 9 {
10     ElemType *elem;
11     int top;
12     int capactiy;
13 }TStack,TNode;
14 
15 int StackInit(TStack &s)//顺序栈的初始化
16 {
17     s.elem =(ElemType*)malloc(sizeof(ElemType) * Max);
18     if (!s.elem)
19         exit(-1);
20     s.top = 0;
21     s.capactiy = Max;
22     return 0;
23 }
24 
25 void StackDestory(TStack& s)//销毁栈
26 {
27     if (!s.elem)
28         return;
29     free(s.elem);
30     s.elem = nullptr;
31     s.capactiy = 0;
32     s.top = 0;
33 }
34 
35 void StackClear(TStack& s)//清空栈
36 {
37     s.top = 0;
38 }
39 
40 bool StackEmpty(TStack* s)//顺序栈是否为空
41 {
42     return s->top == 0;
43 }
44 
45 
46 bool StackPush(TStack* s, ElemType e)//顺序栈入栈
47 { 
48     s->elem[s->top++] = e;
49     return true;
50 }
51 
52 bool StackPop(TStack* s)///顺序栈出栈
53 {
54     if (StackEmpty(s)||s->top == 0)
55     {
56         return false;
57     }
58     else
59     {
60         --s->top;
61         return true;
62     }
63 }
64 
65 ElemType StackTop(TStack s)//顺序栈栈顶元素查询
66 {
67     return s.elem[--s.top];
68 }
69 
70 void StackShow(TStack s)//顺序栈的遍历
71 {
72     for (int i = 0; i < s.top; ++i)
73     {
74         cout << s.elem[i] << " ";
75     }
76 }
77 
78 int main() {
79     TStack s ;
80     StackInit(s);
81     StackPush(&s, 2);
82     StackPush(&s, 3);
83     StackPush(&s, 4);
84     StackPush(&s, 5);
85     StackShow(s);
86     cout << endl;
87     cout << StackTop(s) << endl;
88     StackPop(&s);
89     StackShow(s);
90     cout << endl;
91     cout << StackEmpty(&s) << endl;
92     StackClear(s);
93     cout << StackEmpty(&s) << endl;
94     StackDestory(s);
95     return 0;
96 
97 }


原文地址:https://www.cnblogs.com/dhhu007/p/13195560.html