C语言指针(八)--队列

队列在我们生活中随处可见,在数据结构中的队列就是为了解决实际的排队问题。它同样关心的是数据的存取顺序,队列是一种先进先出(FIFO)的数据结构。
队列
同样,这样的数据结构用单向链表实现相比于用数组实现更加有优势。

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

struct Node
{
    int data;
    struct Node *next;
};

struct Queue
{
    struct Node *head;
    struct Node *tail;
};

struct Queue* init()
{
    struct Queue *qe=NULL;
    qe = (struct Queue*)malloc(sizeof(struct Queue));
    if(qe == NULL)
    {
        printf("create queue malloc error \n");
        return NULL;
    }

    qe->head = (struct Node*)malloc(sizeof(struct Node));
    if(qe->head == NULL)
    {
        free(qe);
        printf("create node malloc error\n");
        return NULL;
    }
    qe->head->next = NULL;
    qe->head->data = 0;
    qe->tail = qe->head;
    return qe;
}
//入队
int in(struct Queue *qu, int data)
{
    if(qu == NULL)
    {
        return -1;
    }
    struct Node *pnew = NULL;
    pnew = (struct Node*)malloc(sizeof(struct Node));
    if(pnew == NULL)
    {
        printf("in pnew malloc is fail\n");
        return -1;
    }
    pnew->data = data;
    pnew->next = NULL;
    qu->tail->next = pnew;
    qu->tail = qu->tail->next;
    return 1;
}

int is_empty_linkqueue(struct Queue *qe)
{
    if(qe == NULL)
    {
        return -1;
    }
    return ((qe->head == qe->tail) ? 1 : 0);
}

//出队
int out(struct Queue *qe)
{
    int ret = 0;
    if(qe == NULL)
    {
        return -1;
    }
    if(is_empty_linkqueue(qe) == 1)
    {
        return 0;
    }
    struct Node *pdel = NULL;
    if(qe->head->next == NULL) 
    {
        qe->tail = qe->head;
        return 0;
    }
    pdel = qe->head->next;
    qe->head->next = pdel->next;
    ret = pdel->data; 
    free(pdel);
    pdel = NULL;
    return ret;
}

int main()
{
    struct Queue *queue = NULL;
    int var, i;
    queue = init();
    for (var = 0; var < 10; var++) {
        in(queue, var);
    }

    for (i = 0; i < 10; i++) {
        printf("queue%d:%d\n",i,out(queue));
    }
}

以上是用单向链表的方式实现的队列,用数组实现队列的例子我在此就不给出了。由于用数组实现队列在出队是需要整体移动全队元素,运行效率较低,所以我推荐使用链表的方式实现队列。

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

南波儿万

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

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

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

打赏作者

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

抵扣说明:

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

余额充值