单链表队列的简单实现

  1. 队列(queue): 只允许在表的一端进行插入操作,在另一端进行删除操作的线性表。允许插入的一端叫做队尾(rear),允许删除的一端叫做队头(front)
  2. 特点: 先进先出。

单链表队列为空的判定条件:LinkQueue.front=LinkQueue.rear,即头指针和尾指针均指向头结点
单链表队列不存在的判定条件:LinkQueue.front=LinkQueue.rear=NULL

#include <iostream>
#include <cstdio>
#include <malloc.h>
typedef int QElemType;
typedef bool Status;
using namespace std;

typedef struct QNode
{
    QElemType data;
    struct QNode *next;
}QNode,*QueuePtr;

typedef struct
{
    QueuePtr Qfront;
    QueuePtr Qrear;
}linkQueue;

///初始化一个空的单链表队列
Status InitLinkQueue_Q(linkQueue &Q)
{
    Q.Qfront=(QueuePtr)malloc(sizeof(QNode));
    if(!Q.Qfront)
        return false;
    Q.Qrear=Q.Qfront;
    Q.Qfront->next=NULL;
    return true;
}
///入队列
Status EnLinkQueue_Q(linkQueue &Q,QElemType e)
{
    QNode *p=(QueuePtr)malloc(sizeof(QNode));
    if(!p)
        return false;
    p->data=e;
    p->next=Q.Qrear->next;
    Q.Qrear->next=p;
    Q.Qrear=p;
    return true;
}
///出队列
Status DeLinkQueue_Q(linkQueue &Q,QElemType &e)
{
    QNode *p=Q.Qfront->next;
    if(!p)
        return false;
    Q.Qfront->next=p->next;
    if(p==Q.Qrear)
        Q.Qrear=Q.Qfront;
    e=p->data;
    free(p);
    return true;
}
///Get队头元素
void GetHead_Q(linkQueue Q,QElemType &e)
{
    if(!Q.Qfront)
        printf("The queue is not exist!\n");
    else if(Q.Qfront->next==NULL)
        printf("The queue is NULL!\n");
    else
    {
        e=Q.Qfront->next->data;
        printf("The head element e=%d\n",e);
    }
}
///销毁队列
void DestroyLinkQueue_Q(linkQueue &Q)
{
    while(Q.Qfront)
    {
        Q.Qrear=Q.Qfront->next;
        free(Q.Qfront);
        Q.Qfront=Q.Qrear;
    }
}
///将Q清为空队列
void ClearLinkQueue_Q(linkQueue &Q)
{
    if(Q.Qfront)
    {
        Q.Qrear=Q.Qfront;
        QNode *p=Q.Qfront->next;
        while(p)
        {
            Q.Qfront->next=p->next;
            free(p);
            p=Q.Qfront->next;
        }
    }
}

int main()
{
    linkQueue Q;
    QElemType e;
    InitLinkQueue_Q(Q);
    EnLinkQueue_Q(Q,3);
    EnLinkQueue_Q(Q,5);
    GetHead_Q(Q,e);
    //DeLinkQueue_Q(Q,e);
    //DestroyLinkQueue_Q(Q);
    ClearLinkQueue_Q(Q);
    GetHead_Q(Q,e);
    return 0;
}

参考:《数据结构C语言版》(严蔚敏)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值