链队列的实现

#include 
#include 
#define Datatype int
typedef struct node{
    Datatype data;
    struct node *next;
}QueueNode;




//定义头节点
typedef struct{
    QueueNode *front;
    QueueNode *rear;
}LinkQueue;




//初始化链队列
void InitQueue(LinkQueue *Q)
{
    Q->front = Q->rear = NULL;
}




//判空
int QueueEmpty(LinkQueue *Q)
{
    return(Q->front == NULL && Q->rear == NULL);
}




//入队
void EnLinkQueue(LinkQueue *Q, Datatype v)
{
    QueueNode *p;
    //给新节点分配空间
    p = (QueueNode *)malloc(sizeof(QueueNode));
    p->data = v;
    p->next = NULL;
    if(QueueEmpty(Q))
        Q->front = Q->rear = p;
    else
    {
        //连接队尾
        Q->rear->next = p;
        Q->rear = p;
    }
}




//出队
Datatype DeLinkQueue(LinkQueue *Q)
{
    Datatype i;
    QueueNode *s;
    //判空
    if(QueueEmpty(Q))
        printf("Error,the linkqueue is empty!");
    s = Q->front;
    i = s->data;
    if(Q->front == Q->rear)   //判断队列是否只有一个节点
        Q->front = Q->rear = NULL;
    else
        Q->front = s->next;
    free(s);
    return i;


}




Datatype ReadLinkQueue(LinkQueue *Q)
{
    Datatype i;
    //判空
    if(QueueEmpty(Q))
        printf("Error,the linkqueue is empty!");
    i = Q->front->data;
    return i;
}


int main()
{
    LinkQueue Q;
    Datatype i = 1;
    InitQueue(&Q);
    while(i<=6)
    {
        //入队
        EnLinkQueue(&Q,i);
    }
    printf("DeLinkQueue: %d\n", DeLinkQueue(&Q));
    printf("DeLinkQueue: %d\n", DeLinkQueue(&Q));
    printf("ReadLinkQueue: %d\n", ReadLinkQueue(&Q));
    printf("ReadLinkQueue: %d\n", ReadLinkQueue(&Q));
    EnLinkQueue(&Q,9);
    printf("The all number of the linkqueue:\n");
    while(!QueueEmpty(&Q))
        printf("%d\t",DeLinkQueue(&Q));
    return 0;
}


 
  

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