前言

链队列就是限制了只能在首端和尾端进行插入,删除操作的表。

  • 链队列中需要头节点

  • 实现它需要声明两个结构。QNode存储某一项的数据,和指向下一项的结构指针。
    ListQueue存储指向头节点和尾节点的结构指针。

1
2
3
4
5
6
7
8
9
10
typedef struct QNode
{
ElementType data;
struct QNode *next;
}QNode, *QNodePtr;

typedef struct ListQueue
{
QNodePtr front, rear;
}ListQueue, *ListQueuePtr;
  • 空队列判断条件 front和rear同时指向头节点

操作

插入

1
2
3
4
5
6
7
8
9
10
11
12
13
void EnQueue(ListQueuePtr Q, ElementType e)
{
QNodePtr P = (QNodePtr)malloc(sizeof(QNode));
if(P == NULL)
{
fprintf(stderr, "Out of space.");
exit(1);
}
P->data = e;
P->next = NULL;
Q->rear->next = P;//连接一下后续节点(P)
Q->rear = P;//让rear指向最后
}

删除

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void DeQueue(ListQueuePtr Q, ElementType *e)
{
QNodePtr P;
if(Q->front == Q->rear)
{
fprintf(stderr, "The queue is empty.");
exit(1);
}
P = Q->front->next;
*e = P->data;
Q->front->next = P->next;//即将front的下一个节点,指向front的下下个
if(Q->rear == P)//如果只剩下一个节点,就让rear = front
Q->rear = Q->front;
free(P);
}

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#ifndef _l_queue_h_

typedef int ElementType;

typedef struct QNode
{
ElementType data;
struct QNode *next;
}QNode, *QNodePtr;

typedef struct ListQueue
{
QNodePtr front, rear;
}ListQueue, *ListQueuePtr;

//初始化链队列
void InitQueue(ListQueuePtr Q);
//将元素插入队列最后
void EnQueue(ListQueuePtr Q, ElementType e);
//删除第一个元素(头节点的后一个)
void DeQueue(ListQueuePtr Q, ElementType *e);

void Traverse(ListQueuePtr Q);
#endif
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include<stdio.h>
#include<stdlib.h>
#include "l_queue.h"

void InitQueue(ListQueue *Q)
{
Q->front = Q->rear = (QNodePtr)malloc(sizeof(QNode));
if(Q->front == NULL)
{
fprintf(stderr, "Out of space.");
exit(1);
}
Q->front->next = NULL;
}

void EnQueue(ListQueuePtr Q, ElementType e)
{
QNodePtr P = (QNodePtr)malloc(sizeof(QNode));
if(P == NULL)
{
fprintf(stderr, "Out of space.");
exit(1);
}
P->data = e;
P->next = NULL;
Q->rear->next = P;//连接一下后续节点(P)
Q->rear = P;//让rear指向最后
}

void DeQueue(ListQueuePtr Q, ElementType *e)
{
QNodePtr P;
if(Q->front == Q->rear)
{
fprintf(stderr, "The queue is empty.");
exit(1);
}
P = Q->front->next;
*e = P->data;
Q->front->next = P->next;//即将front的下一个节点,指向front的下下个
if(Q->rear == P)//如果只剩下一个节点,就让rear = front
Q->rear = Q->front;
free(P);
}

void Traverse(ListQueuePtr Q)
{
QNodePtr P = (QNodePtr)malloc(sizeof(QNode));
P = Q->front->next;
while (P != NULL)
{
printf("%d ", P->data);
P = P->next;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<stdio.h>
#include<stdlib.h>
#include "l_queue.h"

int main()
{
ListQueue Q;//定义一个结构
InitQueue(&Q);
for(int i = 0; i < 4; i++)
{
EnQueue(&Q, i);
}
int *e;
DeQueue(&Q, e);
Traverse(&Q);
}