Tejasvi
Tejasvi

Reputation: 23

Insertion at n'th place in Linked List showing Segmentation error

void Insert(int data, int n){
    Node* temp1 = new Node();
    temp1 -> data = data;
    temp1 -> next = NULL;
    if(n == 1){
        temp1 -> next = head;
        head = temp1;
        return;
    }
    else{
        Node* temp2 = head;
        for(int i; i< n-2; i++){
            temp2 = temp2 -> next;
        }
        temp1 -> next = temp2 -> next;
        temp2 -> next = temp1;
    }
}

I' m getting segmentation error on this and i m unable to figure out whats wrong.

Upvotes: 2

Views: 85

Answers (2)

Wasim
Wasim

Reputation: 724

void Insert(int data, int n)
{
   Node* add = new Node();   // Node to be added
   add -> data = data;
   add -> next = NULL;
   
   if(n == 1)
   {
     add -> next = head;
     head = temp1;
     return;
   }
   else
   {
     Node* temp2 = head;
     Node* prev = NULL;  //Previous pointer
     for(int i=0; i< n-2; i++)
      {
          if(i == n)   // n is required Node where we have to add it.
          {
             prev->next = add;
             add->next = temp;
             return;
          }
          else
          {
            prev = temp2;
            temp2 = temp2->next;
          }
      }
    
    }
}

Upvotes: 5

ZBay
ZBay

Reputation: 332

you didn't initialize i in the for loop.

for(int i; i< n-2; i++){
   temp2 = temp2 -> next;
}

Upvotes: 2

Related Questions