在第n个位置插入元素

Inserting element at nth position

本文关键字:插入 元素 位置 在第      更新时间:2023-09-26

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

当前插入节点的下一个next必须设置为当前第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 }