Created
November 20, 2017 18:44
-
-
Save selahssea-zz/5c539681c42d7fac80a939948cec02a2 to your computer and use it in GitHub Desktop.
Array to linked list in javascript
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 ListNode(x) { | |
this.value = x; | |
this.next = null; | |
} | |
function SinglyList(){ | |
this.head = null; | |
} | |
SinglyList.prototype.add = function(data) { | |
currentNode = this.head; | |
for (var i in data){ | |
var newNode = new ListNode(data[i]); | |
if(currentNode == null){ | |
this.head = newNode; | |
this._lenght++; | |
currentNode = this.head; | |
} | |
else { | |
currentNode.next = newNode; | |
currentNode = currentNode.next; | |
} | |
} | |
return this.head; | |
}; | |
var arrayToLinkedlist = function(arr){ | |
if (arr == null) { | |
return []; | |
} | |
if (!Array.isArray(arr)) { | |
throw new TypeError('array-to-linkedlist expects an array.'); | |
} | |
var singly = new SinglyList(); | |
return singly.add(arr); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment