Dav*_*vid 4 python linked-list singly-linked-list
我在练习 LeetCode 问题(诚然很简单)时遇到了我的问题。然而,我真正的问题是关于Python的,而不是问题本身的答案。您将在下面看到完整的问题陈述,然后我解释我的方法,将其与实际解决方案进行对比,然后(最后)提出我的问题。
问题:
编写一个函数来删除单链表中的节点(尾部除外),并且只能访问该节点。
给定链表 -- head = [4,5,1,9],如下所示:

示例1:
Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.
Run Code Online (Sandbox Code Playgroud)
示例2:
Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.
Run Code Online (Sandbox Code Playgroud)
笔记:
我给出了一个快速答案(在 O(n) 时是次优的,但这不是重点),我通过将已删除节点及其右侧的所有节点全部向左移动一个单位来重新分配它们的值。在此示例中,接下来将重新分配括号中的节点:
4->[5]->1->9->None变成4->1->[1]->9->None, 然后4->1->9->[9]->None,最后4->1->9->None。或者至少,这是我从下面编写的代码中所期望的。
Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.
Run Code Online (Sandbox Code Playgroud)
这个答案让我惊讶的是输入链表与输出链表完全相同。这是输出的屏幕截图:
该解决方案的复杂度为 O(1),如下所示以及相应的(正确的)输出。
Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.
Run Code Online (Sandbox Code Playgroud)
为什么会“就地”node.val = node.next.val修改node.next = node.next.next链表的节点,而重新分配node对node = node.next对象引用没有影响node?
node = node.next只是重新分配 的参数deleteNode,这不会影响函数之外的任何内容。
可以这样想:您期望它会发生改变吗x?
x = 1
def f(a):
a = 2
f(x)
Run Code Online (Sandbox Code Playgroud)
不会的。a这里只是 内部的本地参考f。所有重新分配它所做的就是改变对象a所指向的内容。
比较一下:
x = []
def f(a):
a.append(2)
f(x)
Run Code Online (Sandbox Code Playgroud)
这将会改变x。在这里,您不是重新分配本地引用,而是改变本地引用指向的对象。使用第二个代码,node.val = node.next.val更改node. 它改变了对象。
这就是你的两段代码之间的区别。第一段代码只是更改对对象的引用。第二段代码改变了对象本身。