0.定义链式队列的基本结构
typedef struct LinkNode {
ElemType data;
struct LinkNode* next;
}LinkNode;
typedef struct {
LinkNode* front, * rear;
}LinkQueue;
1.初始化链式队列
void InitQueue(LinkQueue& Q)
{
Q.front = Q.rear = (LinkNode*)malloc(sizeof(LinkNode));
Q.front->next = NULL;
}
2.判断队列是为空
Status IsEmpty(LinkQueue Q)
{
if (Q.front == Q.rear)
return true;
else
return false;
}
3.入队
Status EnQueue(LinkQueue& Q, ElemType x)
{
LinkNode* s = (LinkNode*)malloc(sizeof(LinkNode));
if (s == NULL)
return false;
s->data = x;
s->next = NULL;
Q.rear->next = s;
Q.rear = s;
return true;
}
4.出队
Status DeQueue(LinkQueue& Q, ElemType& x)
{
if (Q.front == Q.rear)
return false;
LinkNode* p = Q.front->next;
x = p->data;
Q.front->next = p->next;
if (Q.rear == p)
Q.rear = Q.front;
free(p);
return true;
}
完整代码
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef bool Status;
typedef struct LinkNode {
ElemType data;
struct LinkNode* next;
}LinkNode;
typedef struct {
LinkNode* front, * rear;
}LinkQueue;
void InitQueue(LinkQueue& Q)
{
Q.front = Q.rear = (LinkNode*)malloc(sizeof(LinkNode));
Q.front->next = NULL;
}
Status IsEmpty(LinkQueue Q)
{
if (Q.front == Q.rear)
return true;
else
return false;
}
Status EnQueue(LinkQueue& Q, ElemType x)
{
LinkNode* s = (LinkNode*)malloc(sizeof(LinkNode));
if (s == NULL)
return false;
s->data = x;
s->next = NULL;
Q.rear->next = s;
Q.rear = s;
return true;
}
Status DeQueue(LinkQueue& Q, ElemType& x)
{
if (Q.front == Q.rear)
return false;
LinkNode* p = Q.front->next;
x = p->data;
Q.front->next = p->next;
if (Q.rear == p)
Q.rear = Q.front;
free(p);
return true;
}
int main()
{
LinkQueue Q;
ElemType x = -1;
InitQueue(Q);
EnQueue(Q, 3);
EnQueue(Q, 6);
EnQueue(Q, 8);
EnQueue(Q, 9);
EnQueue(Q, 7);
EnQueue(Q, 5);
for (int i = 1; i < 7; i++)
{
DeQueue(Q, x);
printf("%d\n", x);
}
if (IsEmpty(Q))
{
printf("队列为空\n");
}
else
{
printf("队列非空\n");
}
return 0;
}