栈相关算法实战
一、【模板】栈
1.1 题目描述
本题要求实现一个栈的基本操作,包括入栈、出栈、查询栈顶元素以及获取栈的大小。数据范围较大,需注意变量类型的选择。
1.2 算法思路
实现栈主要有两种方式:
- 使用 C++ STL:利用
std::stack容器,代码简洁,适合快速开发。 - 数组模拟:手动维护栈顶指针和数组,理解底层原理,性能可控。
注意点:题目中涉及的数据范围可能超出 int 范畴,建议使用 unsigned long long 存储数值。
1.3 代码实现
1.3.1 STL 版本
#include <iostream>
#include <stack>
using namespace std;
typedef unsigned long long ULL;
const int N = 1e6 + 10;
int main() {
int t;
cin >> t;
while (t--) {
stack<ULL> stk;
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
string s;
cin >> s;
if (s == "push") {
ULL x;
cin >> x;
stk.push(x);
} else if (s == "pop") {
if (stk.empty()) cout << "Empty" << endl;
else stk.();
} (s == ) {
(stk.()) cout << << endl;
cout << stk.() << endl;
} (s == ) {
cout << stk.() << endl;
}
}
}
;
}


