题解 | #【模板】栈#

【模板】栈

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对栈顶元素进行压栈和出栈操作,构造栈实现的结构,可以直接使用函数来实现栈功能。

全部评论

相关推荐

点赞 评论 收藏
分享
码农索隆:想看offer细节
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务