队列的链接实现

/*队列的链接实现*/
#include<stdio.h>
typedef int Datatype;
typedef struct LinkQueueNode
{
    Datatype data;
    struct LinkQueueNode *next;
}LkQueNode;
typedef struct LkQueue
{
    LkQueNode *front;
    LkQueNode *rear;
}LkQue;
/*队列初始化*/
void InitQueue(LkQue *LQ)
{
    LkQueNode *temp;
    temp=(LkQueNode *)malloc(sizeof(LkQueNode));    /*生成头结点*/
    LQ->front=temp;                         /*队列头指针指向队列头结点*/
    LQ->rear=temp;                          /*队列尾指针指向队列尾结点*/
    (LQ->front)->next=NULL;
}
/*判队列空*/
int EmptyQueue(LkQue *LQ)
{
    if(LQ->rear==LQ->front)
        return 1;
    else
        return 0;
}
/*入队列*/
void EnQueue(LkQue *LQ,Datatype x)
{
    LkQueNode *temp;
    temp=(LkQueNode *)malloc(sizeof(LkQueNode));
    temp->data=x;
    temp->next=NULL;
    (LQ->rear)->next=temp;                  /*新结点入队列*/
    LQ->rear=temp;                          /*置新的队列结点*/
}
/*出队列*/
int OutQueue(LkQue *LQ)
{
    LkQueNode *temp;
    if(EmptyQueue(&LQ))                     /*判队列是否为空*/
    {
        printf("队空!\n");                  /*队列为空,返回0*/
        return 0;
    }
    else                                    /*队列非空*/
    {
        temp=(LQ->front)->next;             /*使temp指向队列首结点*/
        (LQ->front)->next=temp->next;       /*修改头结点的指针域指向新的首结点*/
        if(temp->next==NULL)
            LQ->rear=LQ->front;             /*无首结点时,front和rear都指向头结点*/
        free(temp);
        return 1;
    }
}
/*取队列首元素*/
Datatype Gethead(LkQue LQ)
{
    LkQueNode *temp;
    if(EmptyQueue(&LQ))
        return NULLData;                        /*判队列为空,返回空数据标志。*/
    else
    {
        temp=LQ.front->next;                    /*队列非空,返回队列首结点元素。*/
        return temp->data;
    }
}
main()
{
    LkQue LQ;
    InitQueue(&LQ);
    int x;
    printf("请输入队列元素:\n");
    scanf("%d",&x);
    while(x!=0)
    {
        EnQueue(&LQ,x);
        printf("请输入队列元素:\n");
        scanf("%d",&x);
    }
    printf("输出队列元素:\n");
    while(!EmptyQueue(&LQ))
        {
            x=Gethead(LQ);
            OutQueue(&LQ);
            printf("%d\t",x);
        }
}

你可能感兴趣的:(队列的链接实现)