-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcircular-queue-based-on-linked-list.js
63 lines (57 loc) · 1.29 KB
/
circular-queue-based-on-linked-list.js
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
class Node {
constructor(element) {
this.element = element;
this.next = null;
}
}
class CircularQueue {
constructor() {
this.head = null;
this.tail = null;
}
enqueue(value) {
if (this.head === null) {
this.head = new Node(value);
this.head.next = this.head;
this.tail = this.head;
} else {
const flag = this.head === this.tail;
this.tail.next = new Node(value);
this.tail.next.next = this.head;
this.tail = this.tail.next;
if (flag) {
this.head.next = this.tail;
}
}
}
dequeue() {
if (this.head == null) return -1;
if (this.head === this.tail) {
const value = this.head.element;
this.head = null;
return value;
} else {
const value = this.head.element;
this.head = this.head.next;
this.tail.next = this.head;
return value;
}
}
display() {
let res = 0;
console.log("-------获取dequeue元素------");
while (res !== -1) {
res = this.dequeue();
console.log(res);
}
}
}
const newCircularQueue = new CircularQueue();
// 插入元素
newCircularQueue.enqueue(1);
newCircularQueue.enqueue(2);
newCircularQueue.enqueue(3);
// 获取元素
newCircularQueue.display();
newCircularQueue.enqueue(1);
newCircularQueue.display();