队列

1.3队列(Queue)及实现

1.3.1队列的定义

具有一定操作约束的线性表,插入和删除操作只能在一端插入(AddQ),在另一端删除(DeleteQ)。

1.3.2队列的存储实现

1.3.2.1队列的顺序存储实现

实际上就是一维数组和记录头尾元素的变量front和rear。

 1 #define MaxSize 100
 2 typedef int ElementType;
 3 typedef struct QNode *Queue;
 4 struct QNode {
 5     ElementType Data[MaxSize];
 6     int front;//记录队头的下标
 7     int rear;//记录队尾的下标
 8 };
 9 Queue Q;
10 
11 //初始化
12 Queue CreateQueue() {
13     Queue Q;
14     Q = (Queue)malloc(sizeof(QNode));
15     Q->front = -1;
16     Q->rear = -1;//此时首尾指向一个位置-1
17     return Q;
18 }
19 
20 //判满
21 int IsFull(Queue Q) {
22     //即rear+1和front之间是一个MaxSize的距离
23     return ((Q->rear + 1) % MaxSize == Q->front);
24 }
25 
26 //入队在rear之后添加,并且后移rear
27 void AddQ(Queue Q, ElementType item) {
28     if (IsFull(Q)) {
29         printf("队已满");
30         return;
31     }
32     Q->rear = (Q->rear + 1) % MaxSize;//超出MaxSize循环回放
33     Q->Data[Q->rear] = item;
34 }
35 
36 //判断队是否为空
37 int IsEmpty(Queue Q) {
38     return (Q->front == Q->rear);
39 }
40 
41 //出队 在front之后删除,并且后移front                                     
42 ElementType DeleteQ(Queue Q) {
43     if (IsEmpty(Q)) {
44         printf("队列空");
45         return 0;
46     }
47     Q->front = (Q->front + 1) % MaxSize;//循环取出
48     return Q->Data[Q->front];
49 }

1.3.2.2队列的链式存储实现

 1 typedef int ElementType;
 2 typedef struct QNode *Queue;
 3 struct Node {
 4     ElementType Data;
 5     struct Node* Next;
 6 };
 7 
 8 struct QNode {
 9     struct Node* rear;//指向队尾的结点
10     struct Node* front;//指向队头的结点
11 };
12 
13 //初始化
14 Queue CreateQueue() {
15     Queue Q;
16     Q = (Queue)malloc(sizeof(QNode));//申请一个队列结构体的大小
17     Q->rear = NULL;
18     Q->front = NULL;
19     return Q;
20 }
21 
22 //是否为空
23 int IsEmpty(Queue Q) {
24     return (Q->front==NULL);
25 }
26 
27 //入队
28 void AddQ(Queue Q, ElementType item) {
29     struct Node* node;
30     node = (struct Node*)malloc(sizeof(Node));//申请一个结点的大小
31     node->Data = item;
32     node->Next = NULL;
33     if (Q->rear == NULL) {//此时队列为空
34         Q->front = node;
35         Q->rear = node;
36     }
37     else {
38         Q->rear->Next = node;//结点加到rear后面
39         Q->rear = node;//移动rear到新结点上,故rear依然保持在最后
40     }
41 }
42 
43 //出队
44 ElementType DeleteQ(Queue Q) {
45     if (IsEmpty(Q)) {
46         printf("队列空");
47         return 0;
48     }
49     struct  Node* FrontCell = Q->front;
50     ElementType FrontElem;
51     if (Q->front == Q->rear) {//如果只有一个元素
52         Q->front == NULL;
53         Q->rear = NULL;
54     }
55     else {
56         Q->front = Q->front->Next;
57     }
58     FrontElem = FrontCell->Data;
59     printf("here");
60     free(FrontCell);
61     return FrontElem;
62 }
作者:PennyXia
         
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/PennyXia/p/12591027.html