队列 Queue
温故知新,可跳转直击概念——队列 Queue
队列的完整实现
队列实现参考代码
js
function Queue() {
this._oldestIndex = 1
this._newestIndex = 1
this._storage = {}
}
Queue.prototype.getLength = function() {
return this._newestIndex - this._oldestIndex
}
Queue.prototype.getData = function() {
return this._storage
}
Queue.prototype.enqueue = function(data) {
this._storage[this._newestIndex] = data
this._newestIndex++
}
Queue.prototype.dequeue = function() {
let oldestIndex = this._oldestIndex
let newestIndex = this._newestIndex
let deletedData = null
if (oldestIndex !== newestIndex) {
deletedData = this._storage[oldestIndex]
delete this._storage[oldestIndex]
this._oldestIndex++
return deletedData
}
}
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
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
js
class Stack {
constructor(size = 0, storage = {}) {
this.size = size
this.storage = storage
}
push(data) {
let size = ++this.size
this.storage[size] = data
}
pop() {
let size = this.size
let deletedData = null
if (size) {
deletedData = this.storage[size]
delete this.storage[size]
this.size--
return deletedData
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24