定义栈的顺序存储结构,并初始化栈。创建一个顺序栈,并从键盘输入栈内元素,键盘输入元素e的入线操作,出栈操作,判断栈是否为空,若为空返回值为0,若不为空,返回值为1;
时间: 2024-06-13 16:08:28 浏览: 14
定义栈的顺序存储结构通常使用数组来实现,栈顶指针top指向栈顶元素的位置,初始值为-1。栈的初始化操作就是将top指针赋值为-1。
以下是创建一个顺序栈并实现相关操作的示例代码:
```c++
#include <iostream>
using namespace std;
const int MAXSIZE = 100; // 定义栈的最大容量
struct SeqStack {
int data[MAXSIZE]; // 存储栈内元素的数组
int top; // 栈顶指针
};
// 初始化栈
void InitStack(SeqStack &s) {
s.top = -1;
}
// 判断栈是否为空
bool IsEmpty(SeqStack s) {
return s.top == -1;
}
// 判断栈是否已满
bool IsFull(SeqStack s) {
return s.top == MAXSIZE - 1;
}
// 入栈操作
bool Push(SeqStack &s, int e) {
if (IsFull(s)) {
return false;
}
s.data[++s.top] = e;
return true;
}
// 出栈操作
bool Pop(SeqStack &s, int &e) {
if (IsEmpty(s)) {
return false;
}
e = s.data[s.top--];
return true;
}
int main() {
SeqStack s;
InitStack(s);
int e;
// 从键盘输入栈内元素
cout << "请输入栈内元素(以-1结束):" << endl;
while (cin >> e && e != -1) {
Push(s, e);
}
// 元素入栈操作
cout << "请输入要入栈的元素:" << endl;
cin >> e;
if (Push(s, e)) {
cout << "入栈成功!" << endl;
} else {
cout << "入栈失败,栈已满!" << endl;
}
// 元素出栈操作
if (Pop(s, e)) {
cout << "出栈成功,出栈元素为:" << e << endl;
} else {
cout << "出栈失败,栈已空!" << endl;
}
// 判断栈是否为空
if (IsEmpty(s)) {
cout << "栈为空!" << endl;
} else {
cout << "栈不为空!" << endl;
}
return 0;
}
```
相关推荐
![dev](https://img-home.csdnimg.cn/images/20210720083646.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)