数据结构系列6-队列

实现功能:

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

代码实现:

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

//定义链表节点的结构体
typedef struct node_st
{
    int data;
    struct node_st *next;
}queue;

/*函数声明部分*/
queue *qu_create();                   //创建队列
void qu_enqueue(queue *head,int data);//入队
int qu_dequeue(queue *head);          //出队
void qu_print(queue *head);           //遍历队

int main()
{

    int ret1,ret2;
    queue *head = qu_create(); //创建队
    qu_enqueue(head,1);//入队
    qu_enqueue(head,2);
    qu_enqueue(head,3);
    qu_enqueue(head,4);
    qu_print(head);    //遍历队

    ret1 = qu_dequeue(head); //出队
    ret2 = qu_dequeue(head);
    printf("出队:%d  %d\n",ret1,ret2);
    qu_print(head);

    return 0;
}


/*函数实现部分*/
//创建队列
queue *qu_create()
{
    queue *head = malloc(sizeof(*head));//头节点
    head->data = 0;  //队列的长度
    head->next = NULL;

    return head;
}


//入队(尾插法)
void qu_enqueue(queue *head,int data)
{
    queue *tail = head;  //尾节点
    queue *new = malloc(sizeof(*new));//新节点
    new->data = data;//新节点的数据

    int i = 0;
    //循环找尾节点
    while(tail->next != NULL)
    //for(i=0;i<head->data;i++)
    {
        tail = tail->next;
    }
    new->next = tail->next;//新节点成为新尾节点,指针域指向NULL
    tail->next = new;//旧的尾节点指向新的尾节点
    head->data ++;//队列的长度+1
}

//出队(删除第1个有效节点)
int qu_dequeue(queue *head)
{
    if(head->data==0)  //队列为空
    {
        return 0;
    }
    else
    {
        queue *node = head->next;//第1个有效节点
        int data = node->data;//保存数据
        head->next = node->next;//删除node
        free(node);
        head->data --;  //队列长度-1

        return data; //返回删除的数据
    }
}

//遍历队列
void qu_print(queue *head)
{
    queue *node = head->next;//第1个有效节点
    while(node)  //当节点不为NULL时
    {
        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、付费专栏及课程。

余额充值