和循环队列采用数组实现顺序存储不同,队列的链式存储和单链表非常类似,依然带头节点,采用尾插法和头部删除法,代码如下:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
typedef int Elem;
//链表
typedef struct LinkNode {
Elem data;
struct LinkNode *next;
}LinkNode;
//队列
typedef struct{
LinkNode* front, * rear;
}LinkQueue;
//初始化
void InitLinkQueue(LinkQueue& Q)
{
Q.front = Q.rear = (LinkNode*)malloc(sizeof(LinkNode));
Q.front->next = NULL;
}
//判空
bool IsEmpty(LinkQueue Q)
{
if (Q.front = Q.rear)
{
return true;
}
return false;
}
//入队
void InLinkQueue(LinkQueue& Q, Elem x)
{
LinkNode* p = (LinkNode*)malloc(sizeof(LinkNode));
p->data = x;
p->next = NULL;
Q.rear->next = p;
Q.rear = p;
}
//出队
bool OutLinkQueue(LinkQueue& Q, Elem& x)
{
if (Q.front == Q.rear)
{
return false;
}
LinkNode* s;
s = Q.front->next;
x = s->data;
Q.front->next = s->next;
if (s == Q.rear)
{
Q.front = Q.rear;
}
free(s);
return true;
}
int main()
{
LinkQueue Q;
InitLinkQueue(Q);
IsEmpty(Q);
for (int i = 0; i < 6; i++)
{
InLinkQueue(Q, i);
}
for (int i = 0; i < 6; i++)
{
int x;
OutLinkQueue(Q, x);
printf("%3d", x);
}
printf("\n");
return 0;
}