簡體   English   中英

算法問題:如何使用 Python class 更新鏈表?

[英]Algorithm Question: How does linked list gets updated using Python class?

這是合並兩個鏈表的解決方案。 在代碼中,我們使用 place_holder 來避免處理 null 值等情況。 然而,這並不直觀,因為我們在整個代碼中只更新了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

以下可以在Python導師中直觀看到

在while循環之前,place_holder和tail被賦值給同一個object即ListNode():

place_holder = ListNode()
tail = place_holde

在 while 循環的第一次迭代中,根據接受 if 條件的分支將 tail.next 分配給 list1 或 list2,即

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 在第一次迭代中被分配給相同的 object。

在if條件之后,tail被分配到不同的object即

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 將其賦值保留在 function 的末尾,因此返回要么返回 list1,要么返回 list2。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM