forked from wangzheng0822/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCircularQueueBasedOnLinkedList.js
More file actions
71 lines (65 loc) · 1.59 KB
/
CircularQueueBasedOnLinkedList.js
File metadata and controls
71 lines (65 loc) · 1.59 KB
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
/**
* 基于链表实现的循环队列。
*
* Author: nameczz
*/
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 === this.tail) {
const value = this.head.element
this.head = null
return value
} else if (this.head !== null) {
const value = this.head.element
this.head = this.head.next
this.tail.next = this.head
return value
} else {
return -1
}
}
display() {
let res = 0
console.log('-------获取dequeue元素------')
while (res !== -1) {
res = this.dequeue()
console.log(res)
}
}
}
// Test
const newCircularQueue = new CircularQueue()
// 插入元素
newCircularQueue.enqueue(1)
newCircularQueue.enqueue(2)
newCircularQueue.enqueue(3)
// 获取元素
newCircularQueue.display()
newCircularQueue.enqueue(1)
newCircularQueue.display()
// exports.CreatedStack = StackBasedLinkedList