题解 | #【模板】栈#

【模板】栈

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

#include <stdio.h>

#define max 100000

typedef struct yuntian {
    int a[max];
    int  pop;
}* yuntian;

void init(yuntian s) {
    s->pop = 0;
}

void push(yuntian s, int i) {
    s->a[++s->pop] = i;
}

int pop(yuntian s) {
    if (s->pop == 0) return 0;
    return s->a[s->pop--];
}

int top(yuntian s) {
    if (s->pop == 0) return 0;
    return s -> a[s -> pop];
}

int main() {
    int a, b;
    int r;
    char c[100];
    yuntian s = (yuntian)malloc(sizeof(struct yuntian));
    init(s);
    scanf("%d", &a);
    while (a--) {
        scanf("%s", c);
        if (strcmp(c, "push") == 0) {
            scanf("%d", &b);
            push(s, b);
        } else if (strcmp(c, "pop") == 0) {
            r = pop(s);
            if (r) {
                printf("%d\n", r);
            } else printf("error\n");
        } else if (strcmp(c, "top") == 0) {
            r = top(s);
            if (r) {
                printf("%d\n", r);
            } else printf("error\n");
        }
    }
    return 0;
}

全部评论

相关推荐

cpp苦手:一眼ddl
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务