I'm having trouble with taking an array of integers and creating a singly linked list with JavaScript. It sounds easy enough, but there's something I'm just not seeing with the function I have an I'd appreciate any help you can provide.
This is the constructor function I use to make nodes:
function ListNode(val) {
this.val = val;
this.next = null;
}
And this is the function I'm writing that is supposed to take an array and create a linked list out of it. The basic idea is just a while loop that shifts off the first value until there's nothing left to shift:
var createLinkedList = function(array) {
var head = new ListNode(parseInt(array[0]));
array.shift();
while(array.length) {
var prev = new ListNode(parseInt(array[0]));
head.next = head;
prev = head;
array.shift();
}
return head;
}
I've tried running this with a couple basic arrays and it always just returns the last value in the array instead of a linked list. Is there something simple I'm just not seeing here? Thanks in advance.