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

天涯浪子 提交于 2020-07-09 05:47:09

问题


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.


回答1:


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;
          }
      }
    
    }
}



回答2:


you didn't initialize i in the for loop.

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


来源:https://stackoverflow.com/questions/62608756/insertion-at-nth-place-in-linked-list-showing-segmentation-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!