Skip to content

Instantly share code, notes, and snippets.

@sarveshrulz
Created December 27, 2022 18:18
Show Gist options
  • Save sarveshrulz/9e83008aed5aec35881b02323bfe3460 to your computer and use it in GitHub Desktop.
Save sarveshrulz/9e83008aed5aec35881b02323bfe3460 to your computer and use it in GitHub Desktop.
Circular queue by using linked list in JavaScript.
class Node {
constructor(val) {
this.data = val;
this.next = null;
}
}
class CircularQueue {
constructor() {
this.front = null;
this.enqueue = (val) => {
let newnode = new Node(val);
if (!this.front)
this.front = newnode;
else
this.rear.next = newnode;
this.rear = newnode;
this.rear.next = this.front;
}
this.dequeue = () => {
if (!this.front)
console.log("Queue is empty!");
else {
this.front = this.front.next;
this.rear.next = this.front;
}
}
this.display = () => {
let curr = this.front;
do {
console.log(curr.data);
curr = curr.next;
} while (curr != this.front);
}
}
}
const cq = new CircularQueue();
cq.enqueue(10);
cq.enqueue(20);
cq.enqueue(30);
cq.display();
cq.dequeue();
cq.display();
cq.enqueue(40);
cq.display();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment