问题
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