在第n个位置插入元素

时间:2016-11-09 04:32:45

标签: javascript

我在JavaScript中实现了一个链表,我试图在链表中的第n个位置插入一个元素。我能够插入一个元素;但是,列表的其余部分被切断了。例如,如果我有a b f m之类的列表并在c位置插入2,如果我插入并打印,我的列表为a b cf m获取切断了。

以下是我的功能:

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 个答案:

答案 0 :(得分: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 }
相关问题