头文件:#include <stack>
创建一个栈:stack<数据大小类型> stk
返回栈顶元素: stk.push(x)
返回顶: stk.top()
将栈顶元素出栈: stk.pop()
判断栈是否为空: stk.empty()
#include <iostream>
#include <stack>
class MyStack {
private:
std::stack<int> stk;
public:
void push(int x) {
stk.push(x);
}
void pop() {
if (!stk.empty()) {
stk.pop();
}
}
int top() {
if (!stk.empty()) {
return stk.top();
}
return -1; // 栈为空时返回一个特定的值,可以根据实际情况进行修改
}
bool empty() {
return stk.empty();
}
};
int main() {
MyStack stk;
stk.push(1);
stk.push(2);
stk.push(3);
std::cout << stk.top() << std::endl; // 输出3
stk.pop();
std::cout << stk.top() << std::endl; // 输出2
std::cout << stk.empty() << std::endl; // 输出0
return 0;
}