Created
August 24, 2019 17:17
-
-
Save rankitranjan/906b71bc18592a23ef97cce9f9aac2e7 to your computer and use it in GitHub Desktop.
Queue using linkedlist
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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