题解 | 【模板】栈

【模板】栈

https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf?tpId=308&tqId=2111163&sourceUrl=%2Fexam%2Foj%3FquestionJobId%3D10%26subTabName%3Donline_coding_page

#include <iostream>
using namespace std;

int main() {
    int n;
    cin >> n;
    string a;
    int x[n], len=0;
    for (int i=0; i<n; ++i) {
        cin >> a;
        if (a == "pop") {
            if (len > 0) {
                cout << x[--len] << endl;
            }
            else cout << "error" << endl;
        }
        else if (a == "top") {
            if (len > 0) {
                cout << x[len-1] << endl;
            }
            else cout << "error" << endl;
        }
        else {
            int t;
            cin >> t;
            x[len++] = t;
        }
    }
    
}
// 64 位输出请用 printf("%lld")
#include <iostream>
#include <type_traits>
using namespace std;

class stack {
    private:
    int x[100000];
    int top_index = -1;
    public:
    int size() {
        return top_index+1;
    }
    void push(int i) {
        x[++top_index] = i;
    }
    int pop() {
        return x[top_index--];
    }
    int top() {
        return x[top_index];
    }
};

int main() {
    int n;
    cin >> n;
    string a;
    stack x;
    for (int i = 0; i < n; ++i) {
        cin >> a;
        if (a == "pop") {
            if (x.size() > 0) {
                cout << x.pop() << endl;
            } else cout << "error" << endl;
        } else if (a == "top") {
            if (x.size() > 0) {
                cout << x.top() << endl;
            } else cout << "error" << endl;
        } else {
            int t;
            cin >> t;
            x.push(t);
        }
    }

}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

08-21 12:03
门头沟学院 Java
这到底要评估多久呀
投递小米集团等公司10个岗位
点赞 评论 收藏
分享
08-20 15:28
门头沟学院 Java
既然要挂我,就不要一直邀请我投递
投递字节跳动等公司10个岗位
点赞 评论 收藏
分享
半解316:内容充实,细节需要修改一下。 1,整体压缩为一页。所有内容顶格。 2,项目描述删除,直接写个人工作量 修改完之后还需要建议,可以私聊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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