题解 | #【模板】栈#

【模板】栈

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

全部评论

相关推荐

04-18 15:58
已编辑
门头沟学院 设计
kaoyu:这一看就不是计算机的,怎么还有个排斥洗碗?
点赞 评论 收藏
分享
逆流河上万仙退:我觉得佬没必要 学历在这里 去了也不会对履历有很大提升 只是有可能让自己更熟练 是我的话会更倾向于找暑期或者中大厂日常
查看13道真题和解析
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务