-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue.ts
More file actions
77 lines (67 loc) · 1.54 KB
/
queue.ts
File metadata and controls
77 lines (67 loc) · 1.54 KB
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
// Linked lists are better implementations for a Queue. The arrays would need reindexing.
import chalk from "chalk";
class Node<T> {
value: T;
next: Node<T> | null;
constructor(value: T) {
this.value = value;
this.next = null;
}
}
class Queue<T> {
front: Node<T> | null;
rear: Node<T> | null;
length: number;
constructor() {
this.front = null;
this.rear = null;
this.length = 0;
}
peek(): T | null {
if (this.front) return this.front.value;
else return null;
}
enqueue(value: T): T {
const node = new Node(value);
if (!this.rear) {
this.front = node;
this.rear = node;
this.length++;
return value;
}
this.rear.next = node;
this.rear = node;
this.length++;
return value;
}
dequeue(): null | T {
if (this.isEmpty()) {
return null;
}
const poppedValue = this.front!.value;
if (this.length === 1) {
this.front = null;
this.rear = null;
this.length = 0;
return poppedValue;
} else {
this.front = this.front!.next;
this.length--;
return poppedValue;
}
}
isEmpty(): boolean {
return this.length === 0;
}
}
const stack = new Queue();
console.log(chalk.blue("______QUEUE_______"));
stack.enqueue("first");
console.log(chalk.blue(stack.peek())); // first
stack.enqueue("second");
stack.enqueue("third");
console.log(chalk.blue(stack.peek())); // first
for (let i = 0; i < 3; i++) {
console.log(chalk.blue(i + 1 + ": ", stack.dequeue()));
}
console.log(chalk.blue(stack.peek())); // null