gpt4 book ai didi

c++ - 如何修复此段错误?

转载 作者:太空宇宙 更新时间:2023-11-04 13:28:21 26 4
gpt4 key购买 nike

引发错误的行在旁边有注释,我正在尝试从我的链表中删除一个节点,当在要删除的节点旁边设置 previous-> 时,下一个段错误发生。

void LinkedList::removeNode(int k)
{
Node* pre = NULL;
Node* curr = NULL;
Node* temp = NULL;

pre = head;

curr = head->get_next();

for(int i =1; i<=length; i++)
{

if (i == k)
{
temp = curr->get_next();
pre->set_next(temp); // this line causes segmentation error
if(curr == tail)
{
tail = pre;
}
delete curr;
break;
}
pre = curr;
if(curr->get_next() != NULL)
{
temp = curr->get_next();
curr = temp;
}
}

最佳答案

看起来您正在遍历链表,但是有一些神秘的 length 迭代限制,它没有在节点删除代码中修改...

这里有一点优化的代码:

void LinkedList::removeNode(int k)
{

if (head == NULL)
return;

Node* curr = head;
Node* next = NULL;

int i = 0;
while ((next = curr->get_next()) != NULL) {
if (++i == k) {
curr->set_next(next->get_next());

if (next == tail)
tail = curr;

next->set_next(NULL);
delete next;
length--;
break;
}

curr = next;
}
}

关于c++ - 如何修复此段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32534755/

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