forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCircularQueue.js
More file actions
Latest commit
89 lines (78 loc) · 2.03 KB
/
Copy pathCircularQueue.js
File metadata and controls
89 lines (78 loc) · 2.03 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
// Circular Queues offer a quick to store FIFO data with a maximum size.
// Conserves memory as we only store up to our capacity
// It is opposed to a queue which could continue to grow if input outpaces output
// Doesn’t use dynamic memory so No memory leaks
classCircularQueue{
constructor(maxLength){
this.queue=[]
this.front=0
this.rear=0
this.maxLength=maxLength
}
// ADD ELEMENTS TO QUEUE
enqueue(value){
if(this.checkOverflow())return
if(this.checkEmpty()){
this.front+=1
this.rear+=1
}else{
if(this.rear===this.maxLength){
this.rear=1
}elsethis.rear+=1
}
this.queue[this.rear]=value
}
// REMOVES ELEMENTS
dequeue(){
if(this.checkEmpty()){
// UNDERFLOW
return
}
consty=this.queue[this.front]
this.queue[this.front]='*'
if(!this.checkSingleelement()){
if(this.front===this.maxLength)this.front=1
else{
this.front+=1
}
}
returny// Returns the removed element and replaces it with a star
}
// checks if the queue is empty or not
checkEmpty(){
if(this.front===0&&this.rear===0){
returntrue
}
}
checkSingleelement(){
if(this.front===this.rear&&this.rear!==0){
this.front=this.rear=0
returntrue
}
}
// Checks if max capacity of queue has been reached or not
checkOverflow(){
if(
(this.front===1&&this.rear===this.maxLength)||
this.front===this.rear+1
){
// CIRCULAR QUEUE OVERFLOW
returntrue
}
}
// Prints the entire array ('*' represents blank space)
display(output=(value)=>console.log(value)){
for(letindex=1;index<this.queue.length;index++){
output(this.queue[index])
}
}
// Displays the length of queue
length(){
returnthis.checkEmpty() ? 0 : this.queue.length-1
}
// Display the top most value of queue
peek(){
returnthis.queue[this.front]
}
}
export{CircularQueue}