题解 | #【模板】栈#

【模板】栈

https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf

#include <cctype>
#include <iostream>
#include <cstring>
using namespace std;

class Stack {
  private:
    enum {Max = 100000};
    int data[Max];
    int top;
  public:
    Stack() {
        this->top = -1;
    }

    void pushStack(int n) {
        this->data[++top] = n;
    }
    void popStack() {
        if (top != -1)
            cout << data[top--] << endl;
        else
            cout << "error" << endl;
    }
    void topStack() {
        if (top != -1)
            cout << data[top] << endl;
        else
            cout << "error" << endl;
    }
};

int main() {
    int times;
    char str[100] = {0};
    char act[10] = {0};
    int num = 0;
    bool haveSpace = false;
    Stack s;
    cin >> times;
	// 建议此处更换为string处理
    for (int i = 0; i <= times; i++) {
        memset(str, 0, sizeof(str));
        memset(act, 0, sizeof(act));
        cin.getline(str, sizeof(str));

        for (int j = 0; str[j] != '\0'; j++) {
            if (isspace(str[j])) {
                memcpy(act, str, j);
                num = atoi(&str[j + 1]);
                haveSpace = true;
            }
        }
        if (false == haveSpace)
            memcpy(act, str, 3);

        if (!strcmp(act, "push"))
            s.pushStack(num);
        else if (!strcmp(act, "pop"))
            s.popStack();
        else if (!strcmp(act, "top"))
            s.topStack();
        haveSpace = false;
    }
}

全部评论

相关推荐

2024-12-21 10:42
已编辑
江西软件职业技术大学 Java
新宿站不停:该提升学历就提升学历,菜了就多练。没事找牛马公司虐自己是吧? 谁没事说自己“经验少”,这不自己把自己塞剎鼻hr嘴里找🐴吗
点赞 评论 收藏
分享
2024-12-29 15:37
已编辑
西华大学 图像识别
程序员牛肉:去不了,大厂算法卡学历吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务