题解 | #【模板】栈#

【模板】栈

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

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct StackNode {
    int data;
    struct StackNode* next;
}StackNode;

StackNode* initStack() {
    StackNode* S = (StackNode*)malloc(sizeof(StackNode));
    S->data = 0;
    S->next = NULL;
    return S;
}

int isEmpty(StackNode* S) {
    if (S->data == 0 || S->next == NULL) return 1;
    else return 0;
}

void push(StackNode* S, int data) {
    StackNode* node = (StackNode*)malloc(sizeof(StackNode));
    node->data = data;
    node->next = S->next;
    S->next = node;
    S->data ++ ;
}

void pop(StackNode* S) {
    if (isEmpty(S)) printf("error\n");
    else {
        StackNode* p = S->next;
        printf("%d\n", S->next->data);
        S->next = p->next;
        //free(p);
        S->data -- ;
    }
}

void top(StackNode* S) {
    if (isEmpty(S)) printf("error\n");
    else
        printf("%d\n", S->next->data);
}

int main()
{
    StackNode* S = initStack();

    int n;
    scanf("%d", &n);

    char s[5];

    while (n -- )
    {
        int x;
        scanf("%s %d", s, &x);
        if (strcmp(s, "push") == 0) push(S, x);
        if (strcmp(s, "top") == 0) top(S);
        if (strcmp(s, "pop") == 0) pop(S);
    }

    return 0;
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-09 11:30
找工作7个月,投了7000封,3段世界五百强实习,才有一个offer,牛油们肯定比我强吧
码农索隆:不对不对不对,实习经历这么厉害,简历也没少投,问题出在哪呢
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-09 11:15
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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