-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.ts
86 lines (73 loc) · 2.35 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
export class Queue<T> {
public size: number = 0;
private _inputQueue: T[] = [];
private _outputQueue: T[] = [];
private _popIndex: number = 0;
public push(item: T): void {
this._inputQueue.push(item);
this.size++;
}
public pop(): T | undefined {
if(this.size === 0) return undefined;
if (this._outputQueue.length === 0 && this._inputQueue.length > 0) {
this._swapQueues()
}
if(this._popIndex >= this._outputQueue.length) {
this._swapQueues()
}
const item = this._outputQueue.at(this._popIndex);
this._popIndex++;
this.size--;
return item;
}
public first(n: number): T[] {
let firstIndex = this._popIndex;
let count = 0;
let result: T[] = [];
while(count < n && firstIndex <= this.size) {
if(firstIndex >= this._outputQueue.length) {
const element = this._inputQueue.at(firstIndex - this._outputQueue.length);
if(element) {
result.push(element)
}
} else {
const element = this._outputQueue.at(firstIndex);
if(element) {
result.push(element)
}
}
firstIndex++;
count++;
}
return result;
}
private _swapQueues(): void {
this._outputQueue = this._inputQueue;
this._inputQueue = [];
this._popIndex = 0;
}
}
// Without the pop index ; but O(n) sometimes
// export class Queue<T> {
// private _queue: T[] = [];
// private _reverseQueue: T[] = [];
// public size: number = 0;
// public push(item: T): void {
// this._queue.push(item);
// this.size++;
// }
// public pop(): T | undefined {
// console.log(">> pop queue: ", this._queue, "reverse queue: ", this._reverseQueue);
// if (this.size === 0) {
// return undefined;
// }
// if (this._reverseQueue.length === 0) {
// while (this._queue.length > 0) {
// this._reverseQueue.push(this._queue.pop()!);
// }
// }
// console.log("<< pop queue: ", this._queue, "reverse queue: ", this._reverseQueue);
// this.size--;
// return this._reverseQueue.pop();
// }
// }