当仅给出指向节点的指针而未给出头节点时,我正在编写从链接列表中删除节点的代码
/*
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);
}
从链接列表中删除节点
为什么?两者之间有什么区别?
分配给函数的(非引用)自变量对该函数以外的对象无效。(了解指针最重要的是,指针没有什么特别的。)
与方法相同
void f(int x) { x = 1000; }
int main()
{
int x = 0;
f(x);
std::cout << x << std::endl;
}
将打印0
,而不是1000
。
因此,您的第一次尝试不会做任何修改,也没有明显的效果。
您的第二次尝试也有问题-它会复制下一个节点,但不会删除它。如果您的节点是动态分配的,通常是这样,则可能是内存泄漏。
您需要这样的东西:
void deleteNode(Node *node)
{
Node* old = node->next;
*node = *(node->next);
delete old;
}
不过,通过复制节点来修改列表有点不常规,因为如果节点的数据很大,效率很低。通常,您更新列表中的链接,但是要执行此操作,您需要知道上一个节点是什么。