-
POJ-栈的基本操作
栈基础知识:蛮重要的,有详解
题目链接:栈的基本操作
-
思路是基础,但是题目有坑
error的输出:每一组完整的数据,只有可能输出一次error,并且有error情况仍然要把剩余操作做完
看见数据也不大,所以直接定义标记变量Break_flag,出现error情况时置1,不过不跳出循环,等全部操作读入后,如果Break_flag=1,直接输出error,否则输出栈内容(注意是按顺序输出,不是出栈顺序,对此我是直接把数组输出)
记得输出后栈顶置-1
-
代码
#include<iostream>
#include<string>
using namespace std;
#define MAX_SIZE 101
class My_Stack
{
private:
int Data[MAX_SIZE];
int Top;
public:
My_Stack() :Top(-1) {};
bool Empty()
{
return Top == -1;
}
void Push(int val)
{
Data[++Top] = val;
}
int Pop()
{
return Data[Top--];
}
int Put_Data()
{
if (Empty())
return 0;
for (int i = 0; i <= Top; i++)
cout << Data[i] << " ";
cout << endl;
Top = -1;
return 1;
}
};
int main()
{
string Op;
int val;
int Test_Time, Op_Time;
cin >> Test_Time;
while (Test_Time--)
{
My_Stack One_stack;
int Break_flag = 0;
cin >> Op_Time;
while (Op_Time--)
{
cin >> Op;
if (Op == "push")
{
cin >> val;
One_stack.Push(val);
}
else
{
if (One_stack.Empty())
Break_flag = 1;
else
One_stack.Pop();
}
}
if (!Break_flag)
One_stack.Put_Data();
else
cout << "error" << endl;
}
return 0;
}
//error只输出一次
//有error情况仍然要把剩余的操作做完