這是合并兩個鏈表的解決方案。在代碼中,我們使用 place_holder 來避免處理空值等情況。然而,這并不直觀,因為我們只tail在整個代碼中更新,但我們place_holder.next在最后回傳。
我們什么時候更新place_holder?在 while 回圈中,我們只使用 list1 和 list2 節點并更新尾部。但是我們什么時候改變 place_holder 的值呢?
class ListNode:
def __init__(self, val: int = 0, *vals: int) -> None:
self.val = val
self.next = ListNode(*vals) if vals else None
def __str__(self) -> str:
s = f"{str(self.val)}"
if self.next:
s = f" -> {self.next}"
return s
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
place_holder = ListNode()
tail = place_holder
while list1 and list2:
if list1.val < list2.val:
tail.next = list1
list1 = list1.next
else:
tail.next = list2
list2 = list2.next
tail = tail.next
if list1 is None:
tail.next = list2
if list2 is None:
tail.next = list1
return place_holder.next
uj5u.com熱心網友回復:
下面在Python家教中可以直觀的看到
在 while 回圈之前,place_holder 和 tail 被分配給同一個物件,即 ListNode():
place_holder = ListNode()
tail = place_holde
在 while 回圈的第一次迭代中,tail.next 被分配給 list1 或 list2 基于哪個分支接受 if 條件,即
if list1.val < list2.val
tail.next = list1 # tail assigned to list1
list1 = list1.next
else:
tail.next = list2 # tail assigned to list2
list2 = list2.next
這也將 place_holder.next 分配給同一個串列,因為 place_holder 和 tail 在第一次迭代中被分配給同一個物件。
在 if 條件之后,tail 被分配給不同的物件,即
tail = tail.next # this causes place_holder and tail
# to no longer be assigned to the same object
所以在while回圈的后續迭代中,tail在while回圈中不斷更新,但place_holder沒有改變(因為place_holder和tail不再分配給同一個物件)
由于 place_holder.next 將其分配保留在函式末尾,因此 return 要么回傳 list1 要么回傳 list2。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/446408.html
標籤:Python python-3.x 算法 班级
上一篇:操縱n對演算法的O有任何影響嗎?
