题解 | #【模板】栈#

【模板】栈

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;
    }
}

全部评论

相关推荐

10-05 23:02
东北大学 Java
我说句实话啊:那时候看三个月培训班视频,随便做个项目背点八股,都能说3 40w是侮辱价
点赞 评论 收藏
分享
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务