【发布时间】:2019-11-17 00:00:34
【问题描述】:
我在练习一个(诚然简单的)LeetCode 问题时遇到了我的问题。然而,我真正的问题是关于 Python,而不是问题本身的答案。您将在下面看到完整的问题陈述,然后我会解释我的方法,将其与实际解决方案进行对比,然后(最终)提出我的问题。
LeetCode 问题:Delete Node in Linked List
问题:
编写一个函数来删除单链表中的一个节点(除了尾部),只允许访问该节点。
给定链表 --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.
示例 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.
注意:
- 链表至少有两个元素。
- 所有节点的值都是唯一的。
- 给定的节点不会是尾节点,它始终是链表的有效节点。
- 不要从您的函数中返回任何内容。
我的方法:
我给出了一个快速的答案(这在 O(n) 时是次优的,但这不是重点),我将已删除节点和所有节点的值重新分配到它的右边,方法是将它们全部向左移动一个单位.在此示例中,接下来将重新分配括号中的节点:
-
4->[5]->1->9->None变为 -
4->1->[1]->9->None,然后 -
4->1->9->[9]->None,最后是 -
4->1->9->None。
或者至少,这是我对下面编写的代码的期望。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteNode(self, node):
while node != None:
node = node.next
这个答案让我惊讶的是输入链表与输出链表完全相同。这是输出的屏幕截图:
实际解决方案:
solution 的复杂度为 O(1),如下所示,并带有相应的(正确)输出。
class Solution:
def deleteNode(self, node):
node.val = node.next.val
node.next = node.next.next
我的问题:
为什么node.val = node.next.val和node.next = node.next.next“就地”修改了链表的节点,而在node = node.next中重新赋值node对对象node的引用没有影响?
【问题讨论】:
标签: python linked-list singly-linked-list