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.
我在使用整数数组并使用JavaScript创建单链表时遇到了麻烦。这听起来很容易,但有些东西,我只是没有看到我的功能,我很感激你能提供的任何帮助。
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:
这是我正在编写的函数,它应该采用一个数组并从中创建一个链表。基本的想法只是一个while循环,它会移开第一个值,直到没有任何东西可以移动:
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.
我尝试使用几个基本数组运行它,它总是只返回数组中的最后一个值而不是链表。有什么简单的我只是没有看到这里?提前致谢。
1 个解决方案
#1
1
The problem is not with array.shift
, but how you link the nodes together inside the while loop.
问题不在于array.shift,而是在while循环中如何将节点链接在一起。
To chain the nodes together, essentially you need to do:
要将节点链接在一起,基本上你需要做:
var new_node = new ListNode(parseInt(array[0]));
head.next = new_node;
new_node = new ListNode(parseInt(array[1]));
head.next.next = new_node;
new_node = new ListNode(parseInt(array[2]));
head.next.next.next = new_node;
.
.
.
I think you get the idea. So what you want to do is rework your while loop, store a reference of the tailNode
so instead of calling head.next.next.next.next.next = newNode
, you can call tailNode.next = newNode
, and tailNode = newNode
inside the while loop.
我想你应该已经明白了。所以你要做的是重做你的while循环,存储tailNode的引用,而不是调用head.next.next.next.next.next = newNode,你可以在里面调用tailNode.next = newNode和tailNode = newNode while循环。
#1
1
The problem is not with array.shift
, but how you link the nodes together inside the while loop.
问题不在于array.shift,而是在while循环中如何将节点链接在一起。
To chain the nodes together, essentially you need to do:
要将节点链接在一起,基本上你需要做:
var new_node = new ListNode(parseInt(array[0]));
head.next = new_node;
new_node = new ListNode(parseInt(array[1]));
head.next.next = new_node;
new_node = new ListNode(parseInt(array[2]));
head.next.next.next = new_node;
.
.
.
I think you get the idea. So what you want to do is rework your while loop, store a reference of the tailNode
so instead of calling head.next.next.next.next.next = newNode
, you can call tailNode.next = newNode
, and tailNode = newNode
inside the while loop.
我想你应该已经明白了。所以你要做的是重做你的while循环,存储tailNode的引用,而不是调用head.next.next.next.next.next = newNode,你可以在里面调用tailNode.next = newNode和tailNode = newNode while循环。