【发布时间】:2013-08-07 05:59:07
【问题描述】:
只是想知道这个删除链表的实现是否有任何缺陷/不一致/内存泄漏:
// Function to delete the entire linked list
void deleteList(Node** head) {
Node* current = *head;
Node* next;
while (current != 0) {
next = current->next;
delete current;
current = next;
}
*head = 0;
}
编辑:
struct Node {
int data;
Node* next;
Node(int data) : data(data){}
};
【问题讨论】:
-
如果没有
Node的定义,就很难肯定地回答这个问题 -
@TimothyJones:我会把你的“难”提高到“不可能”。
-
如果
head无效,你会崩溃,否则看起来没问题(假设Node::next总是正确初始化)。 -
销毁
int显然不会抛出,但是如果您想将其推广到其他类型,那么在开始销毁节点之前,偏执并更新head是值得的。如果数据析构函数抛出异常,您不希望在head中留下无效指针。
标签: c++ algorithm data-structures linked-list