【牛客刷题专栏】0x02:带头节点单链表实现C数据结构栈

前言


问题描述:

请你实现一个栈。
操作:
push x:将 加x入栈,保证 x为 int 型整数。
pop:输出栈顶,并让栈顶出栈
top:输出栈顶,栈顶不出栈


输入描述:

第一行为一个正整数 n ,代表操作次数。(1≤n≤100000)
接下来的 n ,每行为一个字符串,代表一个操作。保证操作是题目描述中三种中的一种。


输出描述:

如果操作为push,则不输出任何东西。
如果为另外两种,若栈为空,则输出 "error“
否则按对应操作输出。


举例:

//输入:
6
push 1
pop
top
push 2
push 3
pop
//输出:
1
error
3

代码结果:

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

typedef struct Node { //定义数据结构,包含数据域域next域
    int data;//data域
    struct Node* next;//next指针域
} Node;

Node* initList() { //初始化头节点
    Node* Stack = (Node*)malloc(sizeof(Node)); //开辟空间,新建节点
    Stack->data = 0; //栈默认个数为0
    Stack->next = NULL; //栈为空,故头节点next域指向空
    return Stack;
}

bool isEmpty(Node* Stack) { //检查栈是否为空
    if (Stack->data == 0 || Stack->next == NULL)    return 0; //为空返回0
    else                                     return 1;//不为空返回1
}

int top(Node* Stack) { //输出栈顶,栈顶不出栈
    if (isEmpty(Stack) == 0)
        return -1;//栈空,输出栈顶错误
    else
        return Stack->next->data;//输出栈顶
}

int pop(Node* Stack) { //输出栈顶,并让栈顶出栈
    if (isEmpty(Stack) == 0)   return -1; //栈空,出栈错误
    else {
        Stack->data--;//出栈导致栈元素个数减一
        Node* node =
            Stack->next; //新建结点存栈顶元素,用于调整链表顺序后使用
        int n = Stack->next->data; //新建遍历存储栈顶值,用于输出使用
        Stack->next = Stack->next->next; //调整链表顺序,删除栈顶,
        free(node);//释放栈顶节点
        return n;//输出栈顶
    }
}

void push(Node* Stack, int data) { //入栈
    Node* node = (Node*)malloc(sizeof(Node));//开辟空间,新建节点
    node->data = data;//data给到新建节点的数据域
    node->next =
        Stack->next; //新建节点插入头节点与旧的栈顶节点之间,即放在栈顶
    Stack->next = node; //续上
    Stack->data++;//入栈导致栈元素个数加一
}

int main() {
    Node* Stack = initList(); //初始化头节点,创捷栈
    int n = 0;
    scanf("%d", &n);
    while (n--) {
        char* str=(char*)malloc(1*sizeof(char));//VScode中char* str;调试正确,牛客中必须申请堆内存才能正确提交,暂时没弄懂
        scanf("%s", str);
        if (!strcmp(str, "push")) {
            int num = 0;
            scanf("%d", &num);
            push(Stack, num);
            continue;//continue作用为结束本次循环
            //break可以跳出“循环体”,还可以跳出switch
        }
        if (!strcmp(str, "pop")) {
            int num1 = pop(Stack);
            if (num1 == -1)
                printf("error\n");
            else printf("%d\n", num1);
            continue;
        }
        if (!strcmp(str, "top")) {
            int num2 = top(Stack);
            if (num2 == -1)
                printf("error\n");
            else printf("%d\n", num2);
            continue;
        }
    }
}

结束语

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不僈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值