单链表节点删除疑问:为何直接赋值node=node.next会报错?
deleteNode Implementation Fails Hey Alice, great question! Let's break down why your approach isn't working and why the official solution does.
The Core Issue: Variable Assignment vs. Modifying Object Properties
In Python, when you pass a ListNode to a function, you're passing a reference to that object. But when you do:
node = node.next
You're not modifying the original node in the linked list—you're just reassigning the local node variable to point to a different object.
Let's use your example to make this concrete:
Input linked list:
4 -> 5 -> 1 -> 9, and we need to delete node5.
- Before your function runs, the
nodeparameter points to the node with value5, and the previous node (4) has itsnextattribute pointing to this node. - When you do
node = node.next, you're only changing what the local variablenodepoints to (now it points to node1). But the previous node (4) still has itsnextpointing to the original node5. The linked list structure remains unchanged:4 -> 5 -> 1 -> 9. That's why your submission fails—LeetCode checks the original linked list structure, which hasn't been modified.
Why the Official Solution Works
The official approach modifies the properties of the original node instead of reassigning the variable:
node.val = node.next.val node.next = node.next.next
Let's walk through the same example:
- First,
node.val = node.next.valsets the value of node5to1(the value of the next node). Now the list is4 -> 1 -> 1 -> 9. - Then,
node.next = node.next.nextmakes node1(originally node5) point to node9, skipping the original node1. Now the list is4 -> 1 -> 9—exactly what we need.
This works because we're altering the actual object that the previous node is pointing to. The linked list structure is modified in-place, which is what LeetCode expects.
Key Takeaway
In Python, reassigning a function parameter only changes the local variable's reference, not the original object. To modify the linked list, you need to change the attributes of the object that's already part of the list, not just reassign the variable pointing to it.
内容的提问来源于stack exchange,提问作者Alice

