单链表队列的简单实现

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

#include 
#include 
#include 
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;
}

你可能感兴趣的:(structure,data)