定义一个栈,可以对栈进行“压入堆栈”、“弹出栈顶元素”、“清空堆栈”、“获取栈顶元素”等操作。键盘输入一些命令,可以执行上述操作。本题中,栈元素均为整数。栈的最大元素个数为1000。
输入
输入各个命令,它们对应的格式如下:
压入堆栈:push a,a代表压入堆栈的元素,这里push和元素之间用空格分隔。
清空堆栈:clear
获取栈顶元素:top
弹出栈顶元素:pop
当输入的命令为exit时,程序结束。
输出
当输入的命令为pop时,请输出弹出的元素值。
当输入的命令是top时,请输出当前栈顶元素值。
注意,如果没有满足的元素,请输出None。
样例输入
push 1
top
clear
push 2
pop
exit
样例输出
1
2
#include<iostream>
#include<string>
using namespace std;
class SqStackClass {
int* data;
int top;
public:
SqStackClass();
~SqStackClass();
void Push(int e);
bool Pop(int& e);
void clear();
bool GetTop(int& e);
};
SqStackClass::SqStackClass() {
data = new int[1000];
top = -1;
}
SqStackClass::~SqStackClass() {
delete[]data;
}
void SqStackClass::Push(int e) {
top++;
data[top] = e;
}
bool SqStackClass::Pop(int& e) {
if (top == -1)return false;
e = data[top];
top--;
return true;
}
void SqStackClass::clear() {
top = -1;
}
bool SqStackClass::GetTop(int& e) {
if (top == -1)return false;
e = data[top];
return true;
}
int main() {
string s;
SqStackClass p;
while (cin >> s) {
if (s == "push") {
int a;
cin >> a;
p.Push(a);
}
else if (s == "pop") {
int e;
if (p.Pop(e))
cout << e << endl;
else cout << "None" << endl;
}
else if (s == "top") {
int e;
if (p.GetTop(e))
cout << e << endl;
else cout << "None" << endl;
}
else if (s == "clear")
p.clear();
else if (s == "exit") break;
}
return 0;
}