题目描述
现有一个空栈s,按顺序执行n个操作序列,每个操作是下面的两种之一:
- 往s中压入一个正整数k
- 弹出s的栈顶元素,同时将其输出
输入描述
第一行一个整数n(1≤n≤100),表示操作序列的个数;
接下来n行,每行一个操作序列,格式为以下两种之一,分别对应入栈和出栈的操作,其中
push k
表示需要将整数k(1≤k≤100)压入栈,而pop
表示需要弹出栈顶元素:
push k
pop
输出描述
输出多行,每次弹出时输出一行,表示弹出的栈顶元素。如果无法弹出栈顶元素,那么输出
-1
。样例1
输入
8 push 2 pop pop push 5 push 3 push 6 pop pop输出
2 -1 6 3
解释
初始时栈为空,即
[]
。接下来进行以下8
个操作:
push 2
:将2
入栈,此时栈为[2]
;pop
:栈顶元素为2
,因此输出2
,弹出后栈为[]
;pop
:由于栈空,无法弹出元素,因此输出-1
;push 5
:将5
入栈,此时栈为[5]
;push 3
:将3
入栈,此时栈为[5,3]
;push 6
:将6
入栈,此时栈为[5,3,6]
;pop
:栈顶元素为6
,因此输出6
,弹出后栈为[5,3]
;pop
:栈顶元素为3
,因此输出3
,弹出后栈为[5]
。
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
stack<int> s;
string str;
int x;
while(n--){
cin>>str;
if(str == "push"){
cin>>x;
s.push(x);
}
else if(str == "pop"){
if(s.empty()){
cout<<-1<<endl;
}
else{
cout<<s.top()<<endl;
s.pop();
}
}
}
return 0;
}
错误代码:
#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; stack<int> s; string str; int x; while(n--){ cin>>str>>x; //如果在此处就输入 x 的话,代码就完不成全部输入 cin.ignore(); if(str == "push"){ s.push(x); } else if(str == "pop"){ if(s.empty()){ cout<<-1<<endl; } else{ cout<<s.top()<<endl; s.pop(); } } } return 0; }