-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQueue.ts
141 lines (140 loc) · 3.37 KB
/
Queue.ts
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
{
/**
* 普通队列
*/
class Queue {
data: any[];
size: number;
constructor(maxlength: number) {
this.data = [];
this.size = maxlength;
}
/**入队 */
enQueue(value: any) {
if (this.getLength() < this.size) {
this.data.push(value);
return;
}
console.error('The queue is full!');
}
/**出队 */
deQueue(): any {
if (!this.isEmpty()) {
return this.data.shift();
}
}
/**队列长度 */
getLength(): number {
return this.data.length;
}
isEmpty() {
return this.data.length === 0;
}
/**清空队列 */
clear() {
this.data.length = 0;
}
print() {
for (const iterator of this.data) {
console.log(iterator)
}
}
}
/**
* 双向对列
*/
class Dique {
data: any[];
size: number;
constructor(maxlength: number) {
this.data = [];
this.size = maxlength;
}
/**
* 头部入队
* @param value 要插入的值
*/
frontEnQueue(value: any) {
if (this.getLength() < this.size) {
this.data.unshift(value);
return;
}
console.error('The queue is full!');
}
/**
* 尾部入队
* @param value 要插入的值
*/
rearEnQueue(value: any) {
if (this.getLength() < this.size) {
this.data.push(value);
return;
}
console.error('The queue is full!');
}
/**
* 头部出队
*/
frontDeQueue(): any {
if (!this.isEmpty()) {
return this.data.shift();
}
}
/**
* 尾部出队
*/
rearDeQueue(): any {
if (!this.isEmpty()) {
return this.data.pop();
}
}
getLength(): number {
return this.data.length;
}
isEmpty() {
return this.data.length === 0;
}
clear() {
this.data.length = 0;
}
print() {
for (const iterator of this.data) {
console.log(iterator)
}
}
}
/**
* 循环队列
*/
class CycleQueue {
/**队列头 */
front: number = 0;
/**队列尾 */
rear: number = 0;
/**队列大小 */
length: number;
/**当前入队数量 */
count: number = 0;
data: any[] = [];
constructor(maxLength: number) {
this.length = maxLength;
}
// 入队
enQueue(value: any) {
if (this.count === this.length) {
throw new Error('The queue is full!');
}
this.data[this.rear] = value;
this.rear = (this.rear + 1) % this.length;
this.count++;
}
// 出队
deQueue() {
if (this.count === 0) {
throw new Error('The queue is empty!');
}
this.front = (this.front + 1) % this.length;
this.count--;
}
}
}