C语言实现队列(链表)

C语言实现队列

 

原理:

  • 通过单链表实现的队列,队列就是一个尾插头删的单链表,先实现一个链表 ,再实现一个队列包括队头指针队尾指针
  • 在这里插入图片描述

头文件

#ifndef Queue_h
#define Queue_h

#include <stdio.h>

typedef int QDataType;		//数据类型

typedef struct ListNode		//通过链表实现的
{
    QDataType _data;
    struct ListNode* _pNext;
}ListNode,*pListNode;

typedef struct Queue
{
    pListNode _pHead;		//头指针
    pListNode _pTail;		//尾指针
}Queue;

void QueueInit(Queue* q);		//初始化
void QueuePush(Queue* q, QDataType d);//进队列(尾插)
void QueuePop(Queue* q);		//出队列(头删)
int QueueSize(Queue* q);		//求队列大小
int QueueEmpty(Queue* q);		//队列判空
QDataType Front(Queue* q);		//获取队头元素
QDataType Back(Queue* q);		//获取队尾元素

#endif /* Queue_h */

源文件

#include "Queue.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>

pListNode BuyNode(QDataType d)
{
    pListNode new = malloc(sizeof(ListNode));
    new->_data = d;
    new->_pNext = NULL;
    return new;
}

void QueueInit(Queue* q)
{
    assert(q);
    q->_pHead = BuyNode(0);
    q->_pTail =q->_pHead;
}

void QueuePush(Queue* q, QDataType d)
{
    assert(q);
    q->_pTail->_pNext = BuyNode(d);
    q->_pTail = q->_pTail->_pNext;
    
}

void QueuePop(Queue* q)
{
    pListNode dNode = q->_pHead->_pNext;
    if (dNode)
    {
        q->_pHead->_pNext = dNode->_pNext;
        if (q->_pHead->_pNext == NULL) {
            q->_pTail = q->_pHead;
        }//如果只有一个元素,删完后ptail会悬空
        free(dNode);
    } 
}

int QueueSize(Queue* q)
{
    assert(q);
    pListNode pre = q->_pHead->_pNext;
    int count = 0;
    while (pre)
    {
        count++;
        pre = pre->_pNext;
    }
    return count;
}
int QueueEmpty(Queue* q)
{
    return NULL == q->_pHead->_pNext;
    
}
QDataType Front(Queue* q)
{
    return q->_pHead->_pNext->_data;
}
QDataType Back(Queue* q)
{
    return q->_pTail->_data;
}
  • 3
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值