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;
}
}
我对此遇到分段错误,无法弄清楚出了什么问题。
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;
}
}
}
}
你没有在for循环中初始化i。
for(int i; i< n-2; i++){
temp2 = temp2 -> next;
}