Mahmud Adam
Mahmud Adam

Reputation: 3579

Inserting element at nth position

I am implementing a linked list in JavaScript, and I am attempting to insert an element at nth position in the linked list. I am able to insert an element; however, the remaining part of the list gets cut off. For instance, if I have a list like a b f m and insert c at position 2, if I insert and print, my list is a b c and f m gets cut off.

Here are my functions:

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
}

and I am calling insertNth like this list.insertNth(2, "c"). Why is the remaining part of the list cut off after inserting a new node?

Upvotes: 0

Views: 513

Answers (1)

jafarbtech
jafarbtech

Reputation: 7015

Current inserted node's next next must be set to the current Nth node. This is done by adding

node.next = head

Then only it will link to the following nodes

    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 }

Upvotes: 1

Related Questions