题解 | #【模板】栈#
【模板】栈
https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf
#include <iostream>
using namespace std;
int s[100001];
int val ,top=-1;
void push(int val){
top++;
s[top] = val;
}
void pop(){
if(top == -1){
cout << "error" << endl;
return;
}
cout << s[top] << endl;
top--;
}
void top1(){
if(top == -1){
cout << "error" << endl;
return;
}
cout << s[top] << endl;
}
int main() {
int n;//表示操作的次数
cin >> n;
string s;
while(n--){
cin >> s;
if(s == "push"){
cin >> val;
push(val);
}else if(s == "pop"){
pop();
}else if(s == "top"){
top1();
}
}
}
// 64 位输出请用 printf("%lld")
栈的基本规则的代码实现。通过top对栈顶元素进行压栈和出栈操作,构造栈实现的结构,可以直接使用函数来实现栈功能。

查看15道真题和解析