非官方题解|预测|夏令营8月Day9题解
2026-08-19 17:24:02
发布于:浙江
注:本帖为预测8月Day9题目与学习内容,并不代表实际学习内容
T1 模拟栈操作

解析:
本题并不用模拟栈操作,只需要建立一个栈,判断一下字符串是什么操作就行了
C++代码:
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
stack<int> stk;
for(int i=1;i<=n;i++){
string s;
cin>>s;
if(s=="push"){
int x;
cin>>x;
stk.push(x);
}else if(s=="pop"){
if(!stk.empty()){
cout<<"pop "<<stk.top()<<endl;
stk.pop();
}
else{
cout<<"pop fail"<<endl;
}
}else if(s=="top"){
if(!stk.empty()){
cout<<"top = "<<stk.top()<<endl;
}
else{
cout<<"top fail"<<endl;
}
}else if(s=="size"){
cout<<"size = "<<stk.size()<<endl;
}else{
if(stk.empty()){
cout<<"yes"<<endl;
}else{
cout<<"no"<<endl;
}
}
}
return 0;
}
T2 表达式括号匹配

解析:
本题初看很简单,其实也很简单
你不能给正括号和反括号各开一个变量累加,因为会有)(的情况,所以可以用一个栈,如果有(就push_back,有)就pop,最后判断栈是否为空就行了
注意:在pop时你需要判断栈是否为空
C++代码:
#include<bits/stdc++.h>
using namespace std;
stack<char> stk;
int main(){
string s;
cin>>s;
for(int i=0;i<s.size();i++){
if(s[i]=='@')
break;
else if(s[i]=='('){
stk.push(s[i]);
}else if(s[i]==')'){
if(!stk.empty()){
stk.pop();
}
else{
cout<<"NO";
return 0;
}
}
}
if(!stk.empty())
cout<<"NO";
else
cout<<"YES";
return 0;
}
T3 队列操作

解析:
创建一个队列,随后通过输入的字符串进行对应的操作
注:在执行pop时要判断队列是否为空
C++代码:
#include<bits/stdc++.h>
#include <queue>
using namespace std;
int main(){
int n;
queue<int> q;
cin>>n;
for(int i=1;i<=n;i++){
string s;
cin>>s;
if(s=="push"){
int x;
cin>>x;
q.push(x);
}else{
if(!q.empty())
q.pop();
}
}
while(!q.empty()){
cout<<q.front()<<" ";
q.pop();
}
return 0;
}
全部评论 2
aadfl;5
3小时前 来自 浙江
0孩子们你们觉得我能预测成功几题3小时前 来自 浙江
0


























有帮助,赞一个