2016-11-09 121 views
0

我正在JavaScript中实现一个链接列表,并试图在链表中的第n个位置插入一个元素。我可以插入一个元素;然而,名单的剩余部分被切断。例如,如果我有一个像a b f m这样的列表并在2处插入c,如果我插入和打印,我的列表是a b cf 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")。为什么在插入一个新节点后,剩余的部分被切断?

回答

1

当前插入节点的下一个下一个必须设置为当前第N个节点。 这是通过添加

node.next = head 

做那么只有它会链接到以下节点

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) 
node.next = head 
return node 
} 
head.next = this.insert(head.next, index-1, data) 
return head } 
+1

这工作。谢谢。 –