-
Notifications
You must be signed in to change notification settings - Fork 2
/
queue.ts
46 lines (34 loc) · 866 Bytes
/
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
import type { IQueue, ILinkedList } from "../types/interfaces";
import LinkedList from "./linked-List";
class Queue<T> implements IQueue<T> {
head: null | T;
#linkedList: ILinkedList<T>;
#auxiliary: number;
constructor() {
this.#linkedList = new LinkedList();
this.head = null;
this.#auxiliary = -1;
}
push(newValue: T): IQueue<T> {
if (this.#auxiliary === -1) {
this.head = newValue;
this.#auxiliary = 0;
}
this.#linkedList.addLast(newValue);
return this;
}
pop(): T {
const deletedElement = this.#linkedList.deleteFirst();
if (deletedElement === null) {
throw new Error("Operation `pop` is not supported in Empty Queue!");
}
if (deletedElement.next) {
this.head = deletedElement.next.value;
} else {
this.head = null;
this.#auxiliary = -1;
}
return deletedElement.value;
}
}
export default Queue;