插入链表中的第n个位置,显示细分错误 [英] Insertion at n'th place in Linked List showing Segmentation error
本文介绍了插入链表中的第n个位置,显示细分错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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.
推荐答案
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;
}
}
}
}
这篇关于插入链表中的第n个位置,显示细分错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文