You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

单链表节点删除疑问:为何直接赋值node=node.next会报错?

Why Your 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 node 5.

  • Before your function runs, the node parameter points to the node with value 5, and the previous node (4) has its next attribute pointing to this node.
  • When you do node = node.next, you're only changing what the local variable node points to (now it points to node 1). But the previous node (4) still has its next pointing to the original node 5. 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:

  1. First, node.val = node.next.val sets the value of node 5 to 1 (the value of the next node). Now the list is 4 -> 1 -> 1 -> 9.
  2. Then, node.next = node.next.next makes node 1 (originally node 5) point to node 9, skipping the original node 1. Now the list is 4 -> 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:00:27