0
我正在JavaScript中实现一个链接列表,并试图在链表中的第n个位置插入一个元素。我可以插入一个元素;然而,名单的剩余部分被切断。例如,如果我有一个像a b f m
这样的列表并在2
处插入c
,如果我插入和打印,我的列表是a b c
和f m
被切断。在第n个位置插入元素
这里是我的功能:
List.prototype.insertNth = function(index, data){
this.head = this.head.insert(this.head, index, data)
}
Node.prototype.insert = function(head, index, data){
if(index===0){
var node = new Node(data, head)
return node
}
head.next = this.insert(head.next, index-1, data)
return head
}
和我打电话insertNth
这样list.insertNth(2, "c")
。为什么在插入一个新节点后,剩余的部分被切断?
这工作。谢谢。 –