-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathqueue.ts
56 lines (49 loc) · 1.12 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
class ListNode<T = number> {
value: T | undefined
next: ListNode<T> | null
constructor (val: T | undefined = undefined, next = null) {
this.value = val
this.next = next
}
}
class Queue<T=number> {
lead: ListNode<T>
tail: ListNode<T>
_size: number
constructor (collection: T[] = []) {
this.lead = new ListNode<T>()
this.tail = this.lead
this._size = 0
for (const item of collection) this.push(item)
}
size (): number {
return this._size
}
push (value: T): void {
this.tail = this.tail.next = new ListNode(value)
this._size++
}
back (): T {
return this.tail.value!
}
shift (): T | undefined {
if (!this._size) return undefined
const first = this.lead.next!
this.lead.next = first.next
this._size--
if (this._size === 0) this.tail = this.lead
return first.value
}
front (): T | undefined {
if (!this._size) return undefined
return this.lead.next!.value
}
* values (): Generator<T, void, void> {
let node = this.lead.next
while (node) {
yield node.value!
node = node.next
}
}
}
export { ListNode, Queue }