数据结构系列5-栈

实现功能:

  1. 创建栈
  2. 入栈
  3. 出栈
  4. 遍历栈

代码实现:

//栈:先进后出,使用单链表实现栈
#include <stdio.h>
#include <stdlib.h>

//定义栈的结构体
typedef struct node_st
{
    int data;   //数据域
    struct node_st *next;//指针域
}stack;

/*函数声明部分*/
stack *stack_create();                //栈的创建
void stack_push(stack *head,int data);//入栈
int stack_pop(stack *head);           //出栈
void stack_print(stack *head);        //栈的遍历

int main()
{
    stack *head = stack_create();  //创建栈
    stack_push(head,1);            //入栈
    stack_push(head,2);
    stack_push(head,3);
    stack_push(head,4);
    stack_print(head);             //遍历栈

    printf("pop = %d\n",stack_pop(head)); //出栈
    stack_print(head);

    return 0;
}

/*函数实现部分*/
//栈的创建
stack *stack_create()
{
    stack *head = malloc(sizeof(*head)); //栈顶节点
    head->data = 0;
    head->next = NULL;

    return head;
}

//入栈,头插法
void stack_push(stack *head,int data)
{
    stack *new = malloc(sizeof(*new));
    new->data = data;//新节点的数据

    new->next = head->next;//新节点的后继指针指向第1个有效节点
    head->next = new;      //头节点的后继指针指向新节点

    head->data++;    //有效节点数+1
}

//出栈,删除第1个有效节点
int stack_pop(stack *head)
{
    if(head->data == 0)//栈为空
    {
        return 0;
    }
    else
    {
        stack *node = head->next;//第1个有效节点
        int data = node->data;  //保存出栈的数据
        head->next = node->next;//头节点的指针指向出栈的下1节点
        free(node);  //释放内存
        head->data--;//有效节点数-1

        return data;  //返回出栈的数据
    }
}

//栈的遍历
void stack_print(stack *head)
{
    stack *node = head->next;
    while(node)
    {
        printf("%d->",node->data);
        node = node->next;
    }
    printf("NULL\n");
}

运行结果:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

⁽⁽ଘ晴空万里ଓ⁾⁾

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

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

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

打赏作者

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

抵扣说明:

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

余额充值