题解 | #【模板】栈#

【模板】栈

https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf?tpId=308&tqId=2111163&ru=/exam/oj&qru=/ta/algorithm-start/question-ranking&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D308

#include<stdio.h>
#include<string.h>
#define Max_Size 100000
#define true 1
#define false 0
typedef int _bool;
typedef struct{
    int data[Max_Size];
    int top;
}Struct;

void Init_Struct(Struct *S);//初始化栈
_bool push(Struct* S,int e);//将e入栈
_bool pop(Struct* S);//栈顶出栈
void top(Struct* S);//读栈顶元素

int main(void){
    Struct S;
    Init_Struct(&S);//初始化栈S
    int n = 0;//存储题目输入的n,代表操作次数
    scanf("%d",&n);
    char str[5];//存储输入的操作名
    int x = 0;//存储入栈时将入栈的元素
    while(n > 0){
        scanf("%s",str);
        if(strcmp(str,"push") == 0){
            scanf("%d",&x);
            push(&S,x);
        }
        else if(strcmp(str,"pop") == 0){
            if(pop(&S) == false){
                printf("error\n");
            }
        }
        else if(strcmp(str,"top") == 0){
            top(&S);
        }
        n--;
        for(int i = 0; i < 4;i++){
            str[i] = ' ';
        }//将数组初始化不然影响下次输入后的比较
    }
    return 0;
}
void Init_Struct(Struct *S){
    S->top = -1;
}
_bool push(Struct* S,int e){
    if(S->top == Max_Size - 1){
        return false;//栈已满
    }

    S->top = S->top + 1;
    S->data[S->top] = e;
    return true;
}

_bool pop(Struct* S){
    if(S->top == -1){
        return false;//栈为空
    }
    printf("%d\n",S->data[S->top]);
    S->top = S->top - 1;
    return true;
}
void top(Struct* S){
    if(S->top == -1){
        //栈为空
        printf("error\n");
        return ;
    }
    printf("%d\n",(S->data[S->top]));
}

全部评论

相关推荐

小谷围鸡肉卷阿姨:+1,腾子投完一动不动
点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务