顺序栈(SqStack)

本文最后更新于:3 个月前

顺序栈的特点和完整代码实现。

顺序栈(SqStack)

注:SqStack为简写,完整名为Sequential Stack。

特点

  • 栈也是一种线性表。
  • 只允许在一端进行插入和删除的线性表。
  • 先进后出。

完整代码实现

代码结构

  • 定义顺序栈结构
  • 初始化顺序栈
  • 判断顺序栈空方法
  • 顺序栈的进栈方法
  • 顺序栈的出栈方法
  • 顺序栈的读取栈顶元素方法
  • 主函数用以测试

具体实现

1
2
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include<iostream>
#include<string>

using namespace std;

/*
顺序栈表
*/
#define MAXSIZE 10 //栈元素的最大个数

/* 顺序栈表存储结构 */
typedef struct
{
int 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, int e)
{
if (S.top == MAXSIZE-1)//top指的是数组的下标位置
{
return false;
}
S.top++; //指针先+1
S.data[S.top] = e; //新元素入栈
//或者上两步合并
//S.data[++S.top] = e;
return true;
}

/* 出栈 */
bool Pop(SqStack& S, int &e)
{
if (S.top == -1)
{
return false;
}
e = S.data[S.top];
S.top--;
//或者上两步合并
//S.data[S.top--] = e;
return true;
}

/* 读取栈顶元素 */
void GetTop(SqStack S,int &e)
{
if (S.top == -1)
{
return;
}
e = S.data[S.top];
}

/* 主函数 */
int main()
{
SqStack S; //实例化栈
InitStack(S); //初始化栈
cout <<"栈是否为空:" << StackEmpty(S) << endl; //判断栈空
int a = 10; //定义入栈元素a
int b; //定义接收栈顶元素b

cout << "入栈:" << Push(S, a)<< endl;
GetTop(S, b);
cout<<"读取栈顶元素:" <<b <<endl;
cout << "出栈:" << Pop(S, a) << endl;
cout << "栈是否为空:" << StackEmpty(S) << endl;
return 0;
}

顺序栈(SqStack)
https://superlovelace.top/2023/10/11/SqStack/
作者
棱境
发布于
2023年10月11日
更新于
2023年10月31日
许可协议