Skip to content

Instantly share code, notes, and snippets.

@jsprieto10
Created April 22, 2020 06:11
Show Gist options
  • Save jsprieto10/7f97e234bbe38765d67e5ca080e95092 to your computer and use it in GitHub Desktop.
Save jsprieto10/7f97e234bbe38765d67e5ca080e95092 to your computer and use it in GitHub Desktop.
This is and implementations of a Queue in javascript using a double linked list
class Queue {
constructor(){
this.tail = null
this.head = null
this.length = 0;
}
shift(){
let temp = this.head
if (this.length < 2){
this.head = null;
this.tail = null;
}
else{
temp.next.prev = null;
this.head = temp.next
}
this.length--;
return temp.value
}
pop(){
let temp = this.tail;
if (this.length < 2){
this.head = null;
this.tail = null;
}
else{
temp.prev.next = null;
this.tail = temp.prev;
}
this.length--;
return temp.value;
}
unshift(value){
let array = Array.isArray(value) ? value: [value]
for(let i = 0; i < array.length; i++){
let val = array[array.length-i-1]
let n = new Node(val);
if (this.length==0) {
this.head = n
this.tail = n
}
else{
let temp = this.head
n.next = temp
temp.prev = n
this.head = n
}
this.length++
}
return this.length;
}
push(val){
let n = new Node(val);
if (this.length==0){
this.head = n
this.tail = n
}
else{
let temp = this.tail
n.prev = temp
temp.next = n
this.tail = n
}
return this.length++;
}
extend(list){
list.forEach( elem => this.push(elem) );
return this.length;
}
valueOf(){
return this.length!=0;
}
toString(){
let r = []
let curr = this.head
while (curr){
r.push(curr.value);
curr = curr.next
}
return r;
}
}
class Node {
constructor(value){
this.next = null;
this.prev = null;
this.value = value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment