Skip to content

Instantly share code, notes, and snippets.

@project42da
Last active June 4, 2017 08:20
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save project42da/42ce3c8e1b0fb68c056178c3b651ff73 to your computer and use it in GitHub Desktop.
function Node(element){
this.element = element;
this.next = null;
}
function LList(arr){
this.arr = arr;
this.head = new Node("head");
}
LList.prototype.find = function(item){
var currNode = this.head;
while(currNode.element != item){
currNode = currNode.next;
}
return currNode;
}
LList.prototype.insert = function(newElement, item){
var newNode = new Node(newElement);
var current = this.find(item);
newNode.next = current.next;
current.next = newNode;
}
LList.prototype.findLast = function(){
var currNode = this.head;
while(currNode.next != null){
currNode = currNode.next;
}
return currNode;
}
function solution(arr){
var list = new LList(arr);
var current = 0;
while(current != -1){
if(list.head.next == null){
list.insert(arr[current], "head");
}else if (current == 0 && list.head.next != null) {
break;
}else{
list.insert(arr[current], current);
}
current = arr[current];
}
return list.findLast().element;
}
var input = [1,4,-1,3,2];
console.log(solution(input));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment