题解 | #【模板】栈#

【模板】栈

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

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

#define MAX 100001
typedef struct Stack{
    int data[MAX];
    int top;
}* PStack,Stack;

PStack getStack(){
    PStack Lstack = (PStack)malloc(sizeof(Stack));
    Lstack->top = 0;
    return Lstack;
}

void push(PStack stack,int val){
    stack->data[stack->top] = val;
    stack->top++;
}
int pop(PStack stack){
    if (stack->top == 0) {
        return -1;
    }
    stack->top--;
    return stack->data[stack->top];
}

int top(PStack stack){
    if (stack->top == 0) {
        return -1;
    }
    return stack->data[stack->top-1];
}

int main() {
    PStack Lstack = getStack();
    int count = 0;

    scanf("%d",&count);
    char* str = (char *)malloc(6*sizeof(char));
    for (int i = 0; i < count; i++) {
        scanf("%s",str);
        if (!strcmp(str,"push")) {
            int num=0;
            scanf("%d",&num);
            push(Lstack,num);
        }else if (!strcmp(str,"pop")) {
            int num=0;
            if ((num = pop(Lstack))==-1) {
                printf("error\n");
            }else {
                printf("%d\n",num);
            }
        }else if (!strcmp(str,"top")) {
            int num=0;
            if ((num = top(Lstack))==-1) {
                printf("error\n");
            }else {
                printf("%d\n",num);
            }
        }
    }
    return 0;
}

全部评论

相关推荐

有担当的灰太狼又在摸鱼:零帧起手查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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