-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueues.ts
77 lines (60 loc) · 1.21 KB
/
queues.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
import { Node } from './node';
export class Queue<T> {
public size: number;
constructor(
public front: Node<T> | null = null,
public rear: Node<T> | null = null
) {
this.front = front;
this.rear = rear;
this.size = 0;
}
isEmpty() {
return !this.front && !this.rear;
}
enqueue(value: T) {
const newNode = new Node<T>(value);
if (!this.front && !this.rear) {
this.front = newNode;
this.rear = newNode;
} else {
this.rear?.setNextNode(newNode);
this.rear = newNode;
}
this.size++;
}
dequeue() {
if (this.isEmpty()) {
throw new Error('Queue is empty!');
}
const frontNode = this.front;
if (frontNode) {
this.front = frontNode.getNextNode();
this.size--;
}
}
peek() {
return this.rear?.getValue();
}
}
export class ArrayBasedQueue<T> {
public queue: Array<T>;
constructor() {
this.queue = [];
}
isEmpty() {
return this.queue.length === 0;
}
enqueue(value: T) {
this.queue.push(value);
}
dequeue() {
if (this.isEmpty()) {
throw new Error('Queue is empty');
}
this.queue.shift();
}
peek() {
return this.queue[this.queue.length - 1];
}
}