Skip to content

Instantly share code, notes, and snippets.

@dlucidone
Last active February 6, 2019 05:19
Show Gist options
  • Save dlucidone/707e726a0eccc1fcd369fefc862612be to your computer and use it in GitHub Desktop.
Save dlucidone/707e726a0eccc1fcd369fefc862612be to your computer and use it in GitHub Desktop.
Linked list JS
function Node(data){
this.data = data;
this.next = null;
}
function LinkedList(){
this.length=0;
this.head = null;
}
LinkedList.prototype.add = function(value){
var node = new Node(value);
if(this.head == null){
this.head = node;
this.length++;
}
else{
current = this.head;
while(current.next!=null){
current = current.next;
}
current.next = node;
this.length++;
}
}
LinkedList.prototype.removeAtNthPosition = function(position){
var current = this.head;
var currentPrev = null;
var nodeToDelete = this.head;
if(position == 1){
this.head = null;
}
else if(this.length < position){
this.head = current.next;
}
else{
var index = 0;
while(nodeToDelete.next!=null ){
if(index < position){
nodeToDelete = nodeToDelete.next;
index++;
}
}
while(nodeToDelete!=null){
currentPrev = current;
current = current.next
nodeToDelete = nodeToDelete.next;
}
currentPrev.next = current.next;
this.length --;
}
}
LinkedList.prototype.display= function(){
for(var i=0;i<this.length;i++){
console.log(this.head.data+"->")
this.head = this.head.next;
}
}
var ll = new LinkedList();
// add
ll.add(235);
ll.add(245);
ll.add(123);
ll.add(223);
ll.removeAtNthPosition(2);
ll.display();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment