forked from TheAlgorithms/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcircular_queue.ts
More file actions
109 lines (98 loc) · 2.65 KB
/
circular_queue.ts
File metadata and controls
109 lines (98 loc) · 2.65 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/**
* Circular Queue implementation using array.
*
* @template T The type of the elements in the queue.
* @param {T[]} queue The array that holds the elements of the queue.
* @param {number} frontIndex The index of the front element of the queue.
* @param {number} rearIndex The index of the rear element of the queue.
* @param {number} size The size of the queue.
*/
export class CircularQueue<T> {
private queue: T[]
private frontIndex: number
private rearIndex: number
private size: number
constructor(size: number) {
this.queue = new Array(size)
this.frontIndex = -1
this.rearIndex = -1
this.size = size
}
/**
* Adds an item to the queue.
*
* @param item The item being added to the queue.
*/
enqueue(item: T): void {
if (
(this.frontIndex == 0 && this.rearIndex == this.size - 1) ||
this.rearIndex == (this.frontIndex - 1) % (this.size - 1)
) {
throw new Error('Queue is full')
} else if (this.frontIndex == -1) {
this.frontIndex = 0
this.rearIndex = 0
this.queue[this.rearIndex] = item
} else if (this.rearIndex == this.size - 1 && this.frontIndex != 0) {
this.rearIndex = 0
this.queue[this.rearIndex] = item
} else {
this.rearIndex++
this.queue[this.rearIndex] = item
}
}
/**
* Removes an item from the queue and returns it.
*
* @throws Queue Underflow if the queue is empty.
* @returns The item that was removed from the queue.
*/
dequeue(): T | undefined {
if (this.frontIndex == -1) {
throw new Error('Queue is empty')
}
const item = this.queue[this.frontIndex]
if (this.frontIndex == this.rearIndex) {
this.frontIndex = -1
this.rearIndex = -1
} else if (this.frontIndex == this.size - 1) {
this.frontIndex = 0
} else {
this.frontIndex++
}
return item
}
/**
* Returns the item at the front of the queue.
*
* @returns The item at the front of the queue or null if the queue is empty.
*/
peek(): T | null | undefined {
if (this.frontIndex == -1) {
return null
}
return this.queue[this.frontIndex]
}
/**
* Checks if the queue is empty.
*
* @returns {boolean} Whether the queue is empty or not.
*/
isEmpty(): boolean {
return this.frontIndex == -1
}
/**
* Returns the number of items in the queue.
*
* @returns {number} The number of items in the queue.
*/
length(): number {
if (this.frontIndex == -1) {
return 0
}
if (this.rearIndex >= this.frontIndex) {
return this.rearIndex - this.frontIndex + 1
}
return this.size - (this.frontIndex - this.rearIndex - 1)
}
}