简答题
偏难
#7527
stack or queue(2024-3-6级) 栈和队列都是常用的线性结构,它们都提供两个操作: Push:加入一个元素。 Pop:弹出一个元素。 不同的是…
stack or queue(2024-3-6级)
栈和队列都是常用的线性结构,它们都提供两个操作:
Push:加入一个元素。
Pop:弹出一个元素。
不同的是,栈是”先进后出”,而队列则是”先进先出”。
给出一个线性结构的进出顺序,判定这个结构是栈还是队列。
时间限制:1000
内存限制:65535
输入
第一行输入一个整数t,代表有t组测试数据 对于每组测试数据,第一行输入一个整数n,代表操作的次数。 随后输入n行,每行包含两个整数 type val。 当type = 1时,表示该次操作为push操作,val表示进入的数字。当type=2时,表示该次操作为pop操作,val代表出来的数字。 3<=n<=2000
输出
每组测试数据输出一行。 输出该组数据对应的线性结构,”Stack” 或者 “Queue”。 题目保证是栈或者队列的一种。
样例输入
2 6 1 1 1 2 1 3 2 3 2 2 2 1 4 1 1 1 2 2 1 2 2
样例输出
Stack Queue
答案与解析
正确答案:<pre class="brush:cpp;toolbar:false">//参考代码1
#include <deque>
#include <iostream>
using namespace std;
int main() {
int t;
scanf("%d", &t);
deque<int> ds; // imitating stack
for (int i = 0; i < t; i++) {
int n;
bool tag = false;
scanf("%d", &n);
for (int j = 0; j < n; j++) {
int type, val;
scanf("%d%d", &type, &val);
if (tag)
continue;
if (type == 1) {
ds.push_back(val);
} else {
int s = ds.back();
ds.pop_back();
if (s != val) {
printf("Queue\n");
tag = true;
}
}
}
if (!tag)
printf("Stack\n");
ds.clear();
}
}</pre><pre class="brush:cpp;toolbar:false">//参考代码2
#include <bits/stdc++.h>
using namespace std;
string Struct;
bool H;
int push[2005];
int pop[2005];
int main()
{
int t;
cin>>t;
while(t--)
{
int n,type,val,Innum=0,Outnum=0;
cin>>n;
for(int i=0;i<n;++i)
{
cin>>type>>val;
if(type==1)
{
push[Innum++]=val;
}
else
{
pop[Outnum++]=val;
}
}
int num=min(Innum,Outnum);
H=false;
for(int i=0;i<num;++i)
{
if(push[i]!=pop[i])
{
Struct="Stack";
H=true;
break;
}
}
if(!H) Struct="Queue";
cout<<Struct<<endl;
}
return 0;
}</pre><p><br/></p>
这道题暂未补解析。