logo AlgoBeat OnlineJudge
登录 注册

#122题解

作者: ZhuTY14  ·  发布于 2026-06-03 20:59:10  ·  最后修改于 2026-06-03 21:08:08
已通过
审核员:sonny2011 管理员 · 2026-06-03 21:08:08

为我投的题写篇题解

题意

实现一个栈,使它实现入栈、出栈、查询栈顶、查询元素个数的功能。

思路

STL 中有 stack 数据结构实现上述函数,具体不细讲,想必都知道

提示

  1. 与原题不同的是,本题取消多测,数据太难造
  2. 注意特判空栈;
  3. 只有在输出时需要换行,小心输出空行导致 WA ;

代码

#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;

int main(){
	ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
	stack<ull> s;
	int n;
	cin >> n;
	string c;
	ull x;
	while (n--) {
		cin >> c;
		if(c == "push"){
			cin >> x;
			s.push(x);
		}
		else if(c == "pop"){
			if(s.empty()){
				cout <<"Empty\n";
			}
			else {
				s.pop();
			}
		}
		else if(c == "query"){
			if(s.empty()){
				cout <<"Anguei!\n";
			}
			else {
				cout << s.top() <<'\n';
			}
		}
		else if(c == "size"){
			cout << s.size() <<'\n';
		}
	}
	return 0;
}

暂无评论

登录 后即可评论。