题解 | #【模板】栈#

【模板】栈

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;
}

全部评论

相关推荐

小浪_Coding:找硬件测试,也可兼顾软测欧, 简历还可以的 ,注意排版,项目写的有条理一点, 然后个人技能多加点, 润色好简历之后就开始沟通海投了,深圳,东莞这边做硬件相关的公司还不少, 医疗类,仪器类的都可以尝试
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-24 12:26
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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