只想知道在删除链表的实现中是否存在任何缺陷/不一致/内存泄漏:
// 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){}
};
答案 0 :(得分:1)
如果你通过引用而不是指针传递头指针,那将是更多的C ++:
void deleteList(Node * & head)
{
// (...)
head = nullptr; // NULL in C++ pre-11
}
另外,为了使代码更加整洁,您可以在循环中移动next
的声明:
while (current != 0)
{
Node * next = current->next;
delete current;
current = next;
}
我对内存泄漏的唯一担心是关于正确释放节点的内容,但是因为你存储了一个简单的int,所以不应该有任何问题。
假设你的列表有节点的有效指针,并且头指针也有效,其他一切看起来都很好。