2024年第一道,简单题开篇

【模板】栈

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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node{
    int data;
    struct node* next;
}node;
typedef struct stack{
    struct node* root;
}stack;
void init_stack(stack* s){
    s->root = (node*)malloc(sizeof(node));
    s->root->next= NULL;
}
void push(stack* s,int data){
    node* newnode = (node*)malloc(sizeof(node));
    newnode->data = data;
    newnode->next = s->root->next;
    s->root->next=newnode;
}
void pop(stack*s){
    if(s->root->next == NULL){
        printf("error\n");
    } else {
        node* first = s->root->next;
        printf("%d\n",first->data);
        s->root->next = first->next;
        free(first);
    }
}

void top(stack*s){
    if(s->root->next == NULL){
        printf("error\n");
    } else {
        node* first = s->root->next;
        printf("%d\n",first->data);
    }
}

int main() {
    int n,d;
    stack s;
    init_stack(&s);
    
    while (scanf("%d", &n) != EOF) {
        for(int i=0;i<n;i++){
            char a[5];
            scanf("%s",a);
            if (strcmp(a,"push") == 0){
                scanf("%d",&d);
                push(&s, d);
            } else if(strcmp(a,"pop") == 0){
                pop(&s);
            } else if(strcmp(a,"top") == 0){
                top(&s);
            }
        }
    }
    return 0;
}

全部评论

相关推荐

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