POJ-stack or queue

  • POJ-stack or queue


题目链接:stack or queue

  • 思路与坑

要通过给定的一系列操作判断栈或是队列,那么定义一个栈模拟,如果每步都契合就算栈否则就队列

定义一个队列去模拟也一样

说坑啦~

一定要把数据全部读入,不能得到结果就跳出,这样会导致部分输入数据等到下次循环才被读入,造成

Runtime Error

所以如果得知不匹配,定义一个标记变量,先用小本本记录下来,等到当前测试组全部数据读入再判断栈或队列

  • 代码

#include<iostream>
#include<stack>	
using namespace std;
 //数据结构与算法Mooc(第三章栈与队列3stack_or_queue )
int main()
{
	int Test_Time;
	int Op, Val;
	int Op_time;
	
	cin >> Test_Time;
	while (Test_Time--)
	{
		int Flag = 0;
		stack<int> Model;
		cin >> Op_time;
		while (Op_time--)
		{
			cin >> Op >> Val;
			if (Op == 1)
			{
				Model.push(Val);
			}
			else
			{
				if (Model.top() == Val)
					Model.pop();
				else
				{
					Flag = 1;
				}
			}
		}
		if (Flag)
			cout << "Queue" << endl;
		else
			cout << "Stack" << endl;
	}
	return 0;
}

//最坑莫过于如果判定不是栈后不能直接跳出,需要模拟整个过程,否则没有输入的数据会影响后面测试

猜你喜欢

转载自blog.csdn.net/SZU_Crayon/article/details/81302822