gpt4 book ai didi

c++ - 在链接列表中的第 n 个位置插入显示段错误

转载 作者:行者123 更新时间:2023-12-01 14:36:42 28 4
gpt4 key购买 nike

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

}
}

关于c++ - 在链接列表中的第 n 个位置插入显示段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62608756/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com