-
Notifications
You must be signed in to change notification settings - Fork 1
/
node-queue.ts
47 lines (42 loc) · 867 Bytes
/
node-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
import { IQueue } from '@/types'
import { NodeItem } from '@/algs4/1-3/node-item'
/**
* 先进先出队列(链表实现)
*/
export default class Queue<T> implements IQueue<T> {
public first: NodeItem<T>
public last: NodeItem<T>
private N: number
constructor() {
this.N = 0
this.first = null
this.last = null
}
isEmpty(): boolean {
return this.N === 0
}
size(): number {
return this.N
}
enqueue(item: T) {
const oldLast = this.last
this.last = new NodeItem<T>()
this.last.item = item
this.last.next = null
if (this.isEmpty()) {
this.first = this.last
} else {
oldLast.next = this.last
}
this.N++
}
dequeue(): T {
const item = this.first.item
this.first = this.first.next
if (this.isEmpty()) {
this.last = null
}
this.N--
return item
}
}