Skip to content

Instantly share code, notes, and snippets.

@rankitranjan
Created August 24, 2019 17:17
Show Gist options
  • Save rankitranjan/906b71bc18592a23ef97cce9f9aac2e7 to your computer and use it in GitHub Desktop.
Save rankitranjan/906b71bc18592a23ef97cce9f9aac2e7 to your computer and use it in GitHub Desktop.
Queue using linkedlist
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class Queue {
constructor(){
this.first = null;
this.last = null;
this.length = 0;
}
peek() {
return this.first;
}
enqueue(value){
const newNode = new Node(value);
if (this.length === 0) {
this.first = newNode;
this.last = newNode;
} else {
this.last.next = newNode;
this.last = newNode;
}
this.length++;
return this;
}
dequeue(){
if (!this.first) {
return null;
}
if (this.first === this.last) {
this.last = null;
}
const holdingPointer = this.first;
this.first = this.first.next;
this.length--;
return this;
}
}
const myQueue = new Queue();
myQueue.peek();
myQueue.enqueue('Joy');
myQueue.enqueue('Matt');
myQueue.enqueue('Pavel');
myQueue.peek();
// myQueue.dequeue();
// myQueue.dequeue();
// myQueue.dequeue();
// myQueue.peek();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment