-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCircularQueue.ts
More file actions
79 lines (67 loc) · 1.95 KB
/
CircularQueue.ts
File metadata and controls
79 lines (67 loc) · 1.95 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
class CircularQueue <T> {
private queue: any[];
private currentLength: number;
private rear: number;
private front: number;
constructor(public capacity: number) {
this.queue = new Array<T>(capacity);
this.currentLength = 0;
this.rear = -1;
this.front = -1;
}
enqueue(value: T): string | void {
if(this.isFull()) return console.error("Queue is full");
this.rear = (this.rear + 1) % this.capacity;
this.queue[this.rear] = value;
this.currentLength += 1;
if(this.front === -1) this.front = this.rear;
}
dequeue(): T {
this.checkEmpty();
const value = this.queue[this.front];
this.queue[this.front] = null;
this.front = (this.front + 1) % this.capacity;
this.currentLength--;
if(this.isEmpty()){
this.front = -1;
this.rear = -1;
}
return value;
}
peek(): T {
this.checkEmpty();
return this.queue[this.front];
}
print(): void {
this.checkEmpty();
let i;
let str = '';
for(i = this.front; i !== this.rear; i = (i + 1) % this.capacity){
str += this.queue[i] + ' ';
}
str += this.queue[i];
console.log(str);
}
checkEmpty(): string | void {
if(this.isEmpty()) return console.error("Queue is empty");
}
isFull(): boolean {
return this.currentLength === this.capacity;
}
isEmpty(): boolean {
return this.currentLength === 0;
}
}
const circularQueue = new CircularQueue<number>(5);
console.log('Is empty: ', circularQueue.isEmpty());
circularQueue.enqueue(10);
circularQueue.enqueue(20);
circularQueue.enqueue(30);
circularQueue.enqueue(40);
circularQueue.enqueue(50);
circularQueue.print();
console.log(circularQueue.dequeue());
console.log('Peeks: ', circularQueue.peek());
circularQueue.print();
circularQueue.enqueue(60);
circularQueue.print();