栈的秘密
请修改编辑器中的代码,完成以下功能:程序中定义了一个抽象基类 Stack 和其派生类 ArrayStack,用于实现一个字符栈的功能。请在指定位置补充代码,使 ArrayStack 类能够正确地分配内存、存储字符并实现栈的基本操作:入栈 (push) 和出栈 (pop)。程序的功能包括:将字符依次入栈,然后按逆序依次出栈并输出结果。 不需要输入。 输出示例: c, b, a
// proj2.cpp
#include <iostream>
using namespace std;
class Stack { //抽象栈类的定义
public:
virtual void push(char c) = 0; //元素进栈
virtual char pop() = 0; //元素出栈
};
class ArrayStack : public Stack { //派生栈类的定义
char *p; // 指向存放栈元素的字符数组
int maxSize; // 栈的最大容量
int top; // 栈顶位置
public:
ArrayStack(int s) //s表示栈的最大容量
{
top = -1; //top值为-1表示栈空
maxSize = s;
//********found********
p = new _____________; //为字符数组动态分配maxSize个单元的栈空间
}
~ArrayStack()
{
//********found********
delete ______; // 释放字符数组p的存储空间
}
void push(char c)
{
if (top==maxSize-1) {
cerr<<"Overflow\!"<<endl; return;
}
//********found********
p[++top]=__________; // 将字符c压入栈内
}
char pop()
{
if (top==-1) {
cerr<<"Underflow\!"<<endl; return '\0';
}
//********found********
return_____________; // 弹出并返回栈顶元素
}
};
int main()
{
ArrayStack as(10);
as.push('a'); as.push('b'); as.push('c');
cout <<as.pop()<<", ";
cout<<as.pop()<<", ";
cout<<as.pop()<<endl;
return 0;
}控制台
调试终端
