引发错误的行旁边有注释,我试图从我的链接列表中删除一个节点,并在设置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;
}
}
答案 0 :(得分:0)
看起来你通过链表重复,但有一些神秘的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;
}
}