引起错误的行被注释在旁边,我试图从我的链表中删除一个节点,当在要删除的节点旁边设置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;
}
}