题解 | #【模板】栈#

【模板】栈

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

常规堆栈的运用

#include <stdbool.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#define MAXSIZE 100000
struct stack{
    int data[MAXSIZE];
    int top;
};

void InitStack(struct stack* s){
    s->top = -1;
}

bool push(struct stack* s,int temp){
    if(s->top!=MAXSIZE-1){
        s->data[++s->top] = temp;
        return true;
    }else{
        return false;
    }
}

bool pop(struct stack* s,int* temp){
    if(s->top == -1){
        return false;
    }else{
        *temp = s->data[s->top--];
        return true;
    }
}

bool top(struct stack* sta,int *temp){
    if(sta->top == -1){
        return false;
    }else{
        *temp = sta->data[sta->top];
        return true;
    }
}

int main(){
    int n=0;
    char s[5] = {0};
    int temp;
    struct stack* sta = (struct stack*)malloc(sizeof(struct stack));
    InitStack(sta);
    scanf("%d",&n);
    for(int i = 0;i < n;i++){
        scanf("%s",s);
        if(!strcmp(s,"push")){
            scanf("%d",&temp);
            push(sta,temp);
        }else if(!strcmp(s,"pop")){
            if(pop(sta,&temp)){
                printf("%d\n",temp);
            }else{
                printf("error\n");
            }
            
        }else if(!strcmp(s,"top")){
            if(top(sta,&temp)){
                printf("%d\n",temp);
            }else{
                printf("error\n");
            }
        }
    }
    return 0;
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务