我有一个单链接,循环链接列表,并且正在编写一个析构函数以删除所有节点。析构函数首先将头部与其余部分分开,以防止无限循环,然后循环遍历列表并删除所有节点,最后,循环又回到头部并将其删除。在程序中,我检查以确保指向节点的指针不是NULL,并且运行了调试器,它表明在应该结束循环的一点上它是NULL,但是循环继续并运行到未分配的内存中。这是我的代码:
node<T> *cur = head;
node<T> *nxt = head->next;
if (nxt) cur->next = nullptr;
cur = nxt;
// walk through the list and delete nodes
while (cur) {
cur = cur->next;
delete cur;
}
EDIT:更改为
node<T> *cur = head;
node<T> *nxt = head->next;
if (nxt) cur->next = nullptr;
cur = nxt;
// walk through the list and delete nodes
while (cur) {
nxt = cur->next;
delete cur;
cur = nxt;
}
EDIT 2:再次更改了代码以处理边缘情况,仍然出现相同的问题。
if (head == NULL) return;
else if (head->next == head) delete head;
else {
node<T> *cur = head;
node<T> *nxt = head->next;
cur->next = nullptr;
cur = nxt;
while(cur) {
nxt = cur -> next;
delete cur;
cur = nxt;
}
}
与切断无关,在非圆形列表中删除元素时在列表中遍历的代码也同样会出错。前进指针then删除其指向的内容(下一项)。
您需要删除current项(但是,当然,您还需要在此之前提取其next
字段,因为一旦删除,所有内容都将变得不确定),例如:
while (cur != nullptr) {
node<T> *toDelete = cur;
cur = cur->next;
delete toDelete;
}
就您所需要的完整解决方案而言,算法应该为:
def delCircList(head):
# Ignore empty list.
if head == null:
return
# Special for one-element list.
if head.next == head:
free head
return
# Sever link and set start point.
curr = head.next
head.next = null
# Use normal deletion algorithm.
while curr != null:
toDelete = curr
curr = curr.next
free toDelete