3. 编写类模版,实现顺序栈的功能: (1) 栈的初始化 (2) 判断栈是否为空; (3) 判断栈是否为满; (4) 入栈; (5) 出栈; (6) 销毁。 并写出调用此类模板的完整程序。
时间: 2023-12-12 17:04:35 浏览: 29
好的,这是一个基于模板的顺序栈实现:
```c++
#include <iostream>
using namespace std;
template <typename T>
class SeqStack {
private:
T *data; // 数据区
int top; // 栈顶指针
int maxSize; // 栈的最大容量
public:
SeqStack(int size = 100) { // 构造函数
data = new T[size];
top = -1;
maxSize = size;
}
~SeqStack() { // 析构函数
delete[] data;
}
void clear() { // 清空栈
top = -1;
}
bool isEmpty() { // 判断栈是否为空
return top == -1;
}
bool isFull() { // 判断栈是否为满
return top == maxSize - 1;
}
bool push(T x) { // 入栈
if (isFull()) return false;
data[++top] = x;
return true;
}
bool pop(T &x) { // 出栈
if (isEmpty()) return false;
x = data[top--];
return true;
}
};
int main() {
SeqStack<int> s(10); // 创建一个最大容量为10的整型栈
s.push(1);
s.push(2);
s.push(3);
int x;
while (s.pop(x)) { // 出栈并输出
cout << x << " ";
}
cout << endl;
return 0;
}
```
这个程序中,我们使用了一个模板类 SeqStack,这个类实现了栈的基本功能。在主函数中,我们创建了一个最大容量为10的整型栈,并依次入栈1、2、3,然后出栈并输出。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)