#include <iostream>
#include <string>
using namespace std ;
class stack {
private :
int s[100000] ;
int top_idx = -1 ;
public :
void push(int x) { // 压入栈顶
top_idx ++ ;
s[top_idx] = x ;
}
void pop() { // 从栈顶弹出
if (top_idx >= 0) cout << s[top_idx--] << endl ;
else cout << "error" << endl ;
}
void top() { // 查看栈顶元素
if (top_idx >= 0) cout << s[top_idx] << endl ;
else cout << "error" << endl ;
}
};
int main() {
int n ;
cin >> n ;
stack s ;
for (int i = 0 ; i < n ; i ++ ) {
string op ;
cin >> op ;
if (op == "push") {
int x ;
cin >> x ;
s.push(x) ;
}
if (op == "pop") s.pop() ;
if (op == "top") s.top() ;
}
return 0 ;
}
C++数据结构:栈模板
于 2024-02-23 11:34:14 首次发布