题解 | #【模板】栈#

【模板】栈

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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct stack {
    int* data;
    int top;
    int size;
} stack;
void init(stack* st) {
    st->data = (stack*)malloc(sizeof(stack) * 10);
    st->top = 0;
    st->size = 10;
}
void push(stack* st, int x) {
    if (st->top == st->size) {
        st->size *= 2;
        int* temp = (int*)realloc(st->data, sizeof(stack) * st->size);
        st->data = temp;
    }
    st->data[st->top] = x;
    st->top++;
}
int pop(stack* st) {
    if(st->top==0){
        return -1;
    }else{
        st->top--;
        return st->data[st->top];
    }  
}
int top(stack* st) {
    if(st->top==0){
        return -1;
    }else{
        return st->data[st->top - 1];
    }
}
int main() {
    stack st;
    init(&st);
    int n;
    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        char op[50];
        scanf("%s", op);
        if (strcmp(op, "push") == 0) {
            int x;
            scanf("%d", &x);
            push(&st, x);
        } else if (strcmp(op, "top") == 0) {
            int val = top(&st);
            if (val == -1) {
                printf("error\n");
            }
            else  printf("%d\n",val);
        } else if (strcmp(op, "pop") == 0) {
            int val = pop(&st);
            if (val == -1) {
                printf("error\n");
            }
            else  printf("%d\n",val);
        }
    }
    return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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