#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct LinkNode{
int data;
struct LinkNode *next;
}LinkNode,*LNode;
typedef struct{
LinkNode *front,*rear;
}LinkQueue;
/*
带头节点的链式队列
*/
/*
1. 初始化
*/
void InitQueue(LinkQueue *Q){
// 建立头节点
(*Q).front = (*Q).rear = (LNode)malloc(sizeof(LinkNode));
(*Q).front->next = NULL;
}
/*
2. 判队空
true: 队空;false:不空
*/
bool isEmpty(LinkQueue Q){
if(Q.front == Q.rear) return true;
return false;
}
/*
3. 入队
*/
void EnQueue(LinkQueue *Q,int x){
LNode q = (LNode)malloc(sizeof(LinkNode));
q->data = x;
q->next = NULL;
Q->rear->next = q;
Q->rear = q;
}
/*
4. 出队
*/
bool DeQueue(LinkQueue *Q,int *x){
// 队空时,返回 false
if(Q->front == Q->rear) return false;
// 队首元素出队
*x = (*Q).front->next->data;
LNode l = (*Q).front;
Q->front = l->next;
free(l);
}
/*
打印队列
*/
void printLinkQueue(LinkQueue Q){
LNode f = Q.front->next;
while(f!= NULL){
printf("%d ",f->data);
f = f->next;
}
printf("\n");
}
int main(){
LinkQueue Q;
InitQueue(&Q);
printf("判断队空 %d\n",isEmpty(Q));
printf("打印队列 ");
printLinkQueue(Q);
EnQueue(&Q,1);
EnQueue(&Q,3);
EnQueue(&Q,2);
EnQueue(&Q,1);
printf("打印队列 ");
printLinkQueue(Q);
int i;
bool deQueue = DeQueue(&Q,&i);
printf("出队 %d 队首值 %d \n",deQueue,i);
deQueue = DeQueue(&Q,&i);
printf("出队 %d 队首值 %d \n",deQueue,i);
deQueue = DeQueue(&Q,&i);
printf("出队 %d 队首值 %d \n",deQueue,i);
printf("判断队空 %d\n",isEmpty(Q));
deQueue = DeQueue(&Q,&i);
printf("出队 %d 队首值 %d \n",deQueue,i);
printf("判断队空 %d\n",isEmpty(Q));
deQueue = DeQueue(&Q,&i);
printf("出队 %d 队首值 %d \n",deQueue,i);
deQueue = DeQueue(&Q,&i);
printf("出队 %d 队首值 %d \n",deQueue,i);
}