function LinkedList(head = null, tail= null) {
this.head = head;
this.tail = (tail)? tail: head;
}
function ListNode(val, next=null, previous=null) {
this.val = val;
this.next = next;
this.previous = previous;
}
LinkedList.prototype.unshift = function(node) {
node.next = this.head;
node.previous = null;
if(this.head){this.head.previous = node;}
else {this.tail = node;}
this.head = node;
};
LinkedList.prototype.pop = function() {
let node = this.tail;
if(node.previous)
{
node.previous.next = null;
this.tail = node.previous;
} else {
this.tail = null;
this.head = null;
}
node.previous = null;
return node;
};
LinkedList.prototype.push = function(node) {
node.previous = this.tail || null;
node.next = null;
(this.tail) ? this.tail.next = node : this.head = node;
this.tail = node;
};
LinkedList.prototype.shift = function() {
let node = this.head;
if (this.head.next) {node.next.previous = null;}
else{ this.tail = null; }
this.head = this.head.next;
node.next = null;
return node;
};
LinkedList.prototype.search = function(query) {
let current = this.head;
while(current){
if (current.val === query){
return current;
}
current = current.next;
}
return null;
}
LinkedList.prototype.indexOf = function(val){
const ans = [];
let indx = 0;
let current = this.head;
while(current){
if(current.val === val){
ans.push(indx);
}
current = current.next;
indx++;
}
return ans;
};
const ll = new LinkedList();
const firstNode = new ListNode(1);
const secondNode = new ListNode(5);
const thirdNode = new ListNode(3);
ll.push(firstNode);
ll.push(secondNode);
ll.push(thirdNode);
ll.push(new ListNode(5));
ll.push(new ListNode(8));
ll.push(new ListNode(7));
ll.push(new ListNode(5));
console.log(ll.indexOf(5));
Created
December 18, 2017 16:31
-
-
Save carl-parrish/86877f5e314e384f55a288c444ba060f to your computer and use it in GitHub Desktop.
Double Linked List
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment