我正在做以下LeetCode练习
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 and l2:
if l1.val < l2.val:
temp = head = ListNode(l1.val)
l1 = l1.next
else:
temp = head = ListNode(l2.val)
l2 = l2.next
while l1 and l2:
if l1.val < l2.val:
temp = temp.next = ListNode(l1.val)
#temp.next = temp = ListNode(l1.val)
l1 = l1.next
else:
temp = temp.next = ListNode(l2.val)
#temp.next = temp = ListNode(l2.val)
l2 = l2.next
...
我的问题是,为什么temp = temp.next = ListNode(l1.val)
和temp = temp.next = ListNode(l2.val)
行不起作用,而它们下面的注释行起作用?
它们的含义根本不同:
temp = temp.next = ListNode(l1.val)
相当于:
_node = ListNode(l1.val)
temp = _node
temp.next = _node
而
temp.next = temp = ListNode(l1.val)
相当于:
_node = ListNode(l1.val)
temp.next = _node
temp = _node
第二种方法将当前temp
节点的next
属性分配给新节点,然后将temp
设置为新节点,这是正确的行为。第一个将temp
设置为新节点,然后将其next
属性设置为自身,这是不正确的。