Last active
June 4, 2017 08:20
Star
You must be signed in to star a gist
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(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