-
Notifications
You must be signed in to change notification settings - Fork 314
/
Queue.ts
94 lines (79 loc) · 2.14 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import Node, { DummyHeadNode, DummyTailNode } from './Node';
class Queue<T> {
private _dummyHead: DummyHeadNode;
private _dummyTail: DummyTailNode;
private _length: number;
constructor() {
this._dummyHead = new DummyHeadNode();
this._dummyTail = new DummyTailNode();
this._dummyHead.next = this._dummyTail;
this._dummyTail.prev = this._dummyHead;
this._length = 0;
}
/**
* Adds an element to the back of the Queue.
* @param {*} element
* @return {number} The new length of the Queue.
*/
enqueue(value: T): number {
const node = new Node(value);
const prevLast = this._dummyTail.prev as Node<T> | DummyHeadNode;
prevLast.next = node;
node.prev = prevLast;
node.next = this._dummyTail;
this._dummyTail.prev = node;
this._length++;
return this._length;
}
/**
* Removes the element at the front of the Queue.
* @return {*} The element at the front of the Queue.
*/
dequeue(): T | undefined {
if (this.isEmpty()) {
return undefined;
}
const node = this._dummyHead.next as Node<T>;
const newFirst = node.next as Node<T> | DummyTailNode;
this._dummyHead.next = newFirst;
newFirst.prev = this._dummyHead;
node.next = null;
this._length--;
return node.value;
}
/**
* Returns true if the Queue has no elements.
* @return {boolean} Whether the Queue has no elements.
*/
isEmpty(): boolean {
return this._length === 0;
}
/**
* Returns the element at the front of the Queue.
* @return {*} The element at the front of the Queue.
*/
front(): T | undefined {
if (this.isEmpty()) {
return undefined;
}
return (this._dummyHead.next as Node<T>).value;
}
/**
* Returns the element at the back of the Queue.
* @return {*} The element at the back of the Queue.
*/
back(): T | undefined {
if (this.isEmpty()) {
return undefined;
}
return (this._dummyTail.prev as Node<T>).value;
}
/**
* Returns the number of elements in the Queue.
* @return {number} Number of elements in the Queue.
*/
get length(): number {
return this._length;
}
}
export default Queue;