-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathqueue.cpp
102 lines (90 loc) · 2.02 KB
/
queue.cpp
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include "queue.h"
// 顺序存储
void InitQueue(SqQueue &Q) {
Q.front = Q.rear = 0;
}
void DestoryQueue(SqQueue &Q) {
Q.front = Q.rear = 0;
}
bool EnQueue(SqQueue &Q, ElemType x) {
if ((Q.rear + 1) % MaxSize == Q.front) return false;
Q.data[Q.rear] = x;
Q.rear = (Q.rear + 1) % MaxSize;
return true;
}
bool DeQueue(SqQueue &Q, ElemType &x) {
if (QueueEmpty(Q)) return false;
x = Q.data[Q.front];
Q.front = (Q.front + 1) % MaxSize;
return true;
}
bool GetHead(SqQueue &Q, ElemType &x) {
if (QueueEmpty(Q)) return false;
x = Q.data[Q.front];
return true;
}
bool QueueEmpty(SqQueue Q) {
return (Q.front == Q.rear);
}
// 链式存储
void InitQueue(LiQueue &Q) {
Q.front = Q.rear = (QNode*)malloc(sizeof(QNode));
Q.front->next = NULL;
}
void DestoryQueue(LiQueue &Q) {
ElemType temp;
while (!QueueEmpty(Q)) {
DeQueue(Q, temp);
}
free(Q.front);
Q.front = Q.rear = NULL;
}
bool EnQueue(LiQueue &Q, ElemType x) {
QNode *s = (QNode*)malloc(sizeof(QNode));
if (!s) return false;
s->data = x;
s->next = NULL;
Q.rear->next = s;
Q.rear = s;
return true;
/*
QNode *s = (QNode*)malloc(sizeof(QNode));
if (!s) return false;
s->data = x;
s->next = NULL;
if (Q.front == NULL) { // 第一元素的处理
Q.front = Q.front = s;
}
else {
Q.rear->next = s;
Q.rear = s;
}
return true;
*/
}
bool DeQueue(LiQueue &Q, ElemType &x) {
if (QueueEmpty(Q)) return false;
QNode *p = Q.front->next;
if (Q.rear == p) Q.rear = Q.front;
Q.front->next = p->next;
x = p->data;
free(p);
return true;
/*
if (QueueEmpty(Q)) return false;
QNode *p = Q.front;
Q.front = p->next;
x = p->data;
if (Q.rear == p) Q.rear = Q.front = NULL;
free(p);
return true;
*/
}
bool GetHead(LiQueue &Q, ElemType &x) {
if (QueueEmpty(Q)) return false;
x = Q.front->next->data;
return true;
}
bool QueueEmpty(LiQueue Q) {
return (Q.front == Q.rear);
}