题解 | #【模板】栈#

【模板】栈

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

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

#define MAX_STACK_SIZE 100000

typedef struct stack {
    int st[MAX_STACK_SIZE];
    int index;
} stack;

stack* push(stack* s, int x) {
    if (s->index == MAX_STACK_SIZE - 1) {
        printf("error\n");
        exit(1); // 栈满时退出程序
    }
    s->st[++s->index] = x;
    return s;
}

void pop(stack* s) {
    if (s->index == -1) {
        printf("error\n");
    } else {
        printf("%d\n", s->st[s->index--]);
    }
}

void top(stack* s) {
    if (s->index == -1) {
        printf("error\n");
    } else {
        printf("%d\n", s->st[s->index]);
    }
}

int main() {
    int n;
    stack* a = (stack*)malloc(sizeof(stack)); // 动态分配栈内存
    a->index = -1; // 初始化index为-1,表示栈为空

    while (scanf("%d", &n) != EOF) {
        for (int i = 0; i < n; i++) {
            char s[6];
            scanf("%s", s);
            if (strcmp(s,"push") == 0) {
                int x;
                scanf("%d", &x);
                push(a, x);
            } else if (strcmp(s,"pop") == 0) {
                pop(a);
            } else if (strcmp(s,"top") == 0) {
                top(a);
            }
        }
    }
    free(a); // 释放栈内存
    return 0;
}

全部评论

相关推荐

卡卡罗特ovo:说起云智我就来气,约好了一面,结果面试官没来,ssob上问hr也未读,我还是专门请了半天假在家面试,恶心死了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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