-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path08-circular-queue.js
More file actions
46 lines (43 loc) · 1.06 KB
/
Copy path08-circular-queue.js
File metadata and controls
46 lines (43 loc) · 1.06 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
class CircularQueue{
constructor(size){
this.size = size
this.items = new Array(size).fill(null)
this.front = this.rear = -1
}
enqueue(value){
if( (this.rear + 1)% this.size == this.front ){
console.log("Queue is full")
}else if(this.front === -1){
this.rear = this.front = 0
this.items[this.rear] = value
}else{
this.rear = (this.rear + 1) % this.size
this.items[this.rear] = value
}
}
dequeue(){
if(this.front == -1){
console.log("Queue is empty")
}else if(this.front === this.rear){
console.log(this.items[this.front])
this.front = this.rear = -1
}else{
console.log(this.items[this.front])
this.front = (this.front +1) % this.size
}
}
}
let cq = new CircularQueue(5)
cq.enqueue(10)
cq.enqueue(20)
cq.enqueue(30)
cq.enqueue(40)
cq.enqueue(50)
cq.dequeue()
cq.enqueue(60)
cq.dequeue()
cq.dequeue()
cq.dequeue()
cq.dequeue()
cq.dequeue()
cq.dequeue()