Last active
August 9, 2017 14:59
-
-
Save glebcha/b635fc5913e8758d2a22b9cb2bf76f16 to your computer and use it in GitHub Desktop.
Linked List
This file contains 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
function Node(data) { | |
this.data = data; | |
this.next = null; | |
this.prev = null; | |
} | |
function linkedList() { | |
this.head = null; | |
this.size = 0; | |
} | |
linkedList.prototype.add = function(data) { | |
if(!data || Object.prototype.toString.call(data) === '[object Function]') { | |
throw('Pass valid data'); | |
} | |
var node = new Node(data); | |
var current = this.head; | |
var prev = null; | |
if (!current) { | |
this.head = node; | |
} else { | |
while(current.next) { | |
prev = current; | |
current = current.next; | |
} | |
current.next = node; | |
current.prev = prev; | |
} | |
++this.size; | |
return this; | |
}; | |
linkedList.prototype.remove = function(data) { | |
var current = this.head; | |
if(!current || (current && !current.next)) { | |
throw('Can\'t remove head'); | |
} | |
for(var node = current; node && node.next; node = node.next) { | |
current = node; | |
if(node.next.data === data) { | |
node.next = node.next.next; | |
this.size--; | |
} | |
if (node.prev && node.prev.data === data) { | |
node.prev = node.prev.prev; | |
} | |
} | |
return this; | |
}; | |
linkedList.prototype.peak = function() { | |
return this.head; | |
}; | |
linkedList.prototype.size = function() { | |
return this.size; | |
}; | |
linkedList.prototype.isEmpty = function() { | |
return this.size === 0; | |
}; | |
var list = new linkedList; | |
list.add('text'); | |
list.add('text1'); | |
list.add('text2'); | |
list.add('text3'); | |
list.add('text1'); | |
list.remove('text1'); | |
console.log(list); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment