Skip to content

Instantly share code, notes, and snippets.

@Ivanshamir
Created April 6, 2023 18:48
Show Gist options
  • Select an option

  • Save Ivanshamir/217c194f51f5376cbe813d20463f7ea1 to your computer and use it in GitHub Desktop.

Select an option

Save Ivanshamir/217c194f51f5376cbe813d20463f7ea1 to your computer and use it in GitHub Desktop.
Implement queue using linked list in js
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class Queue {
constructor() {
this.head = null;
this.tail = null;
this.size = 0;
}
enqueue(value) {
let node= new Node(value)
if(this.isEmpty()) {
this.head = node
this.tail = node
} else {
this.tail.next = node
this.tail = node
}
this.size++
}
dequeue(){
if(this.isEmpty()) return
const removedNode = this.head
if (this.size === 1) {
this.head = null
this.tail = null
this.size-- 
return removedNode.value
}
this.head = removedNode.next
this.size--
return removedNode.value
}
peek() {
if(this.isEmpty()) return
return this.head.value
}
isEmpty() {
return this.size === 0
}
print() {
if(this.isEmpty()) return
let data = this.head
while(data) {
console.log(data.value)
data = data.next
}
}
}
let queue = new Queue()
queue.enqueue(5)
queue.enqueue(10)
queue.enqueue(15)
queue.enqueue(20)
console.log(`POPed Value: ${queue.dequeue()}`)
console.log(`Head/peek Value: ${queue.peek()}`)
queue.print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment