【发布时间】:2020-07-18 09:10:31
【问题描述】:
我正在编写一个代码,当只给出指向节点的指针而没有给出头节点时,从链表中删除一个节点
/*
struct Node {
int data;
struct Node *next;
Node(int x) {
data = x;
next = NULL;
}
}*head;
*/
// This function should delete node from linked list. The function
// may assume that node exists in linked list and is not last node
// node: reference to the node which is to be deleted
void deleteNode(Node *node)
{
node=(node->next);
}
不删除列表中的当前指针,但是,
/*
struct Node {
int data;
struct Node *next;
Node(int x) {
data = x;
next = NULL;
}
}*head;
*/
// This function should delete node from linked list. The function
// may assume that node exists in linked list and is not last node
// node: reference to the node which is to be deleted
void deleteNode(Node *node)
{
*node=*(node->next);
}
从链表中删除节点
为什么?方法有什么区别?
【问题讨论】:
-
两者都泄漏内存。第一个泄漏下一个节点。第二个用下一个节点的值覆盖当前节点,然后泄漏现在的前下一个节点。
-
这里的完整解释需要彻底了解指针是什么以及它们是如何工作的。不幸的是,这是一个相当长的话题,stackoverflow 并不能真正替代一本好的 C++ 书籍。所以你只需要独自度过一段美好的时光。
标签: c++ c++11 pointers linked-list singly-linked-list