目录
题目描述
借助函数模板实现栈的操作。
栈是一种先进后出的数据结构,它的插入、删除只能在栈顶位置进行。Push为入栈操作,即插入,Pop为出栈操作,即删除。
栈的操作类似叠盘子,先放的盘子在底下,后放的盘子上面。当要取盘子,就从最上面取。
例如入栈数据1到2再到3,那么3在最上面,1在最下面。当要出栈数据,就是3先出,接着是2,最后是1出栈。
要求你自行定义栈结构,并利用函数模板以及类模板完成对char,int和float型数据的处理。其中,我们定义:
输入
第一行为测试数据数
对于每组测试数据,第一行为数据类型,第二行为操作数
对于每次操作均进行Push或Pop操作。要注意,当空栈弾栈时要给出Error提示
输出
对于每次入栈,不需输出。对于每次出栈,输出出栈元素或给出Error提示。当完成所有操作后,依次逆序输出栈中剩余元素
输入样例1
3
I
6
Push 6
Push 1
Push 1
Pop
Pop
Pop
C
4
Pop
Push a
Push a
Pop
F
8
Push 4.1
Push 4.2
Push 14.1
Push 4.2
Push 1314
Push 1314
Pop
Pop
输出样例1
1 is popped from stack!
1 is popped from stack!
6 is popped from stack!
Empty Stack!
Error!
a is popped from stack!
a
1314 is popped from stack!
1314 is popped from stack!
4.2 14.1 4.2 4.1
AC代码
#include<iostream>
#include<string>
#include<algorithm>
#include<cmath>
#include<iomanip>
using namespace std;
template<class kind>
class stack {
kind p[10000];
int top = -1;
public:
void push() {
kind num;
cin >> num;
p[++top] = num;
}
void pop() {
if (empty()) {
cout << "Error!" << endl;
} else {
cout << p[top--] << " is popped from stack!" << endl;
}
}
bool empty() {
if (top < 0)
return 1;
return 0;
}
void display() {
if (empty())
cout << "Empty Stack!" << endl;
else {
for (int i = top;i>=0;i--)
cout << p[i] << ' ';
cout << endl;
}
}
};
int main() {
int test, count;
char code;
string index;
cin >> test;
while (test--) {
cin >> code >> count;
if (code == 'I') {
stack<int> temp;
while (count--) {
cin >> index;
if (index == "Push")
temp.push();
else
temp.pop();
}
temp.display();
} else if (code == 'C') {
stack<char> temp;
while (count--) {
cin >> index;
if (index == "Push")
temp.push();
else
temp.pop();
}
temp.display();
} else {
stack<float> temp;
while (count--) {
cin >> index;
if (index == "Push")
temp.push();
else
temp.pop();
}
temp.display();
}
}
}