Skip to content

Instantly share code, notes, and snippets.

@selahssea-zz
Created November 20, 2017 18:44
Show Gist options
  • Save selahssea-zz/5c539681c42d7fac80a939948cec02a2 to your computer and use it in GitHub Desktop.
Save selahssea-zz/5c539681c42d7fac80a939948cec02a2 to your computer and use it in GitHub Desktop.
Array to linked list in javascript
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