题解 | #【模板】栈#

【模板】栈

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

#include <iostream>
#include <string>
using namespace std;

// 因为无法得知操作的数据量,采用链式栈的结构
typedef struct LinkedNode{
    int data;
    struct LinkedNode* next;
}LiStack,*Stack;

void push(Stack &S, int e) {
    Stack T = (Stack)malloc(sizeof(LiStack));
    T -> data = e;
    T -> next = S;
    S = T;
}

int pop(Stack &S) {
    Stack T = S;
    int res = S -> data;
    S = S -> next;
    free(T);
    return res;
}

int top(Stack &S) {
    return S -> data;
}

int main() {
  	// 带头结点的链式栈
    Stack S = (Stack)malloc(sizeof(LiStack));
  	// 初始化
    S -> next = NULL;
    S -> data = 0;
    int a;
    string b;
    int c;
    cin >> a;
    while (a >= 1) {
        cin >> b;
        if(b.compare("push") == 0) {
            cin >> c;
        }
        if(b.compare("push") == 0) {
            // 头插法入栈
            push(S, c);
        } else if(b.compare("pop") == 0) {
            if(S -> next == NULL) {
                cout << "error" << endl;
            } else {
                int res = pop(S);
                cout << res << endl;
            }
        } else if(b.compare("top") == 0) {
            if(S -> next == NULL) {
                cout << "error" << endl;
            } else {
                int res = top(S);
                cout << res << endl;
            }
        }
        a--;
    }

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

全部评论

相关推荐

我的名字是句号:接好运
点赞 评论 收藏
分享
头像
03-30 21:02
已编辑
武汉大学 Java
ALEX_BLX:虽然说聊天记录不可信,不过这个趋势确实如此但我觉得也要想到一点就是卷后端的人里真正有“料”的人又有多少,我说的这个料都不是说一定要到大佬那种级别,而是就一个正常的水平。即使是现在也有很多人是跟风转码的,2-3个月速成后端技术栈的人数不胜数,但今时不同往日没可能靠速成进大厂了。这种情况就跟考研一样,你能上考场就已经打败一半的人了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务