#include "pch.h"
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
// 由于链队结点的空间是动态分配的,所以无须考虑队满的运算。
// 队结点类型定义
typedef struct QNode
{
int data;
struct QNode *next;
}QNode;
// 链队类型定义
typedef struct
{
QNode *front;
QNode *rear;
}LiQueue;
// 初始化链队算法
void initQueue(LiQueue *&lqu)
{
lqu = (LiQueue *)malloc(sizeof(LiQueue));
lqu->front = lqu->rear = NULL;
}
// 判断队空的算法
int isQueueEmpty(LiQueue *lqu)
{
if (lqu->rear == NULL || lqu->front ==NULL)
{
return 1;
}
else
{
return 0;
}
}
// 入队
void enQueue(LiQueue *lqu, int x)
{
QNode *p;
p = (QNode *)malloc(sizeof(QNode));
memset(p, 0, sizeof(QNode));
p->data = x;
p->next = NULL;
if (lqu->rear==NULL) // 若队列为空,则新结点是队首结点,也是队尾结点
{
lqu->front = lqu->rear = p;
}
else // 尾插法
{
lqu->rear->next = p;
lqu->rear = p;
}
}
// 出队
void deQueue(LiQueue *lqu,int *x)
{
// QNode *p;
if (isQueueEmpty(lqu)==1)
{
printf("队列为空,不能出队");
}
else
{
*x = lqu->front ->data;
}
if (lqu->front==lqu->rear) // 队列中只有一个结点时候,出队操作 队首队尾设置为空
{
lqu->front = lqu->rear = NULL;
}
else
{
lqu->front = lqu->front->next;
}
}
int main()
{
LiQueue *lqu;
initQueue(lqu);
int a[4] = { 2,6,1,4 };
printf("进队列顺序:2,6,1,4 \n");
for (int i = 0; i < 4; i++)
{
enQueue(lqu,a[i]);
}
printf("出队列顺序:");
while (lqu->front!=NULL)
{
int x;
deQueue(lqu, &x);
printf(" %d ", x);
}
return 0;
}
实现效果如下: