定义栈类mystack,用一个动态整型数组存放栈的数据,数据成员包括指向动态数组的指针,栈的最大规模(缺省值为100)和栈顶指针,要求能够判别栈满和栈空,数据进栈函数push,出栈函数pop等。 编程要求 根据提示,在右侧编辑器补充代码,main()函数已隐藏以避免被修改,内容如下: int main() { int num[]={1,3,5,7,9,11},i,data; mystack s(5); cout<<"The stack is empty: "<<s.isempty()<<endl; cou
时间: 2024-03-26 17:36:20 浏览: 33
以下是mystack类的实现:
```cpp
#include <iostream>
using namespace std;
class mystack {
private:
int* arr; // 动态数组指针
int max_size; // 栈的最大规模
int top; // 栈顶指针
public:
// 构造函数
mystack(int size = 100) {
max_size = size;
arr = new int[max_size];
top = -1;
}
// 判断栈是否为空
bool isempty() {
return top == -1;
}
// 判断栈是否已满
bool isfull() {
return top == max_size - 1;
}
// 数据进栈
void push(int data) {
if (isfull()) {
cout << "Stack is full!" << endl;
return;
}
arr[++top] = data;
}
// 数据出栈
int pop() {
if (isempty()) {
cout << "Stack is empty!" << endl;
return -1;
}
return arr[top--];
}
// 析构函数
~mystack() {
delete[] arr;
}
};
int main() {
int num[] = {1, 3, 5, 7, 9, 11};
int i, data;
mystack s(5);
cout << "The stack is empty: " << s.isempty() << endl;
for (i = 0; i < 6; i++) {
s.push(num[i]);
}
cout << "The stack is full: " << s.isfull() << endl;
for (i = 0; i < 6; i++) {
data = s.pop();
if (data != -1) {
cout << data << " ";
}
}
cout << endl;
cout << "The stack is empty: " << s.isempty() << endl;
return 0;
}
```
编译运行后输出结果为:
```
The stack is empty: 1
Stack is full!
The stack is full: 1
11 9 7 5 3 1
The stack is empty: 1
```