Python編程題46--合併兩個有序鏈表

題目

給定兩個升序鏈表(鏈表中節點存儲的元素是按非遞減順序排列),其頭節點分別爲 head1 和 head2 。請將兩個升序鏈表合併爲一個新的 升序 鏈表並返回,其中新鏈表是通過拼接給定的兩個鏈表的所有節點組成的。

例如:

原鏈表轉換爲列表:[1, 2, 4]、[1, 3, 4]
最終的鏈表轉換爲列表:[1, 1, 2, 3, 4, 4]

原鏈表轉換爲列表:[]、[]
最終的鏈表轉換爲列表:[]

原鏈表轉換爲列表:[]、[1, 3, 4]
最終的鏈表轉換爲列表:[1, 3, 4]

已知 鏈表節點的定義、鏈表與列表相互轉換 的代碼如下:

class ListNode:  # 單鏈表
    def __init__(self, val=0, next=None):
        self.val = val  # 鏈表節點上存儲的元素
        self.next = next  # 指向下一個鏈表節點


def list_to_list_node(numbers):  # 將列表轉換爲單向鏈表,並返回鏈表的頭節點
    dummy_head = ListNode(0)
    pre = dummy_head
    for number in numbers:
        pre.next = ListNode(number)
        pre = pre.next
    pre = dummy_head.next
    return pre


def list_node_to_list(node):  # 將單向鏈表轉換爲列表
    result = []
    while node:
        result.append(node.val)
        node = node.next
    return result

實現思路--迭代

  • 使用 迭代 的方式實現
  • 設置一個虛擬頭節點 dummy_head,同時讓當前節點 cur = dummy_head
  • 當 head1 和 head2 都非空時進行 while 循環,如果 head1 大於 head2 節點下的元素,就讓 cur 通過 next 指向當前元素較小的 head2 ,同時 head2 需要向後移動一位,否則需指向 head1 且 head1 需要向後移動一位
  • 每次循環後 cur 需要向後移動一位,讓其指向下一個節點 cur.next
  • 循環結束後 head1 和 head2 最多會有1個還沒有合併完,也就是說最多有一個非空,但由於兩個鏈表都是有序鏈表,所以不管哪個鏈表非空,其剩餘節點下的元素都會比前面合併鏈表中所有元素都要大,因此,我們只需要讓 cur 通過 next 指向未合併完的鏈表即可
  • 最後返回頭節點時,需要注意新的頭節點是 dummy_head 的下一個節點,即 dummy_head.next

代碼實現

class Solution:
    def mergeTwoLists(self, head1: ListNode, head2: ListNode) -> ListNode:
        dummy_head = ListNode(0)  # 設置一個虛擬頭節點
        cur = dummy_head
        while head1 is not None and head2 is not None:
            if head1.val > head2.val:  # 當前節點通過 next 指向當前元素較小的鏈表節點
                cur.next, head2 = head2, head2.next
            else:
                cur.next, head1 = head1, head1.next
            cur = cur.next
        # 合併後 head1 / head2 最多有1個還沒有合併完,直接讓 cur 通過 next 指向未合併完的鏈表
        cur.next = head1 if head1 is not None else head2
        return dummy_head.next

實現思路--遞歸

  • 使用 遞歸 的方式實現
  • 當 head1 或 head2 都是非空時,需要進行遞歸查找下一個節點
  • 遞歸過程中,我們每次調用函數均會找到兩個鏈表中頭節點下元素較小的一個節點,然後把該節點返回,同時再繼續去找到下一個節點
  • 如果 head1 或 head2 爲空,那麼我們直接返回非空的那一個節點即可,到此遞歸查找結束

代碼實現

class Solution:
    def mergeTwoLists(self, head1: ListNode, head2: ListNode) -> ListNode:
        if head1 is None:  # 如果 head1 爲空,那麼直接返回 head2
            return head2
        elif head2 is None:  # 如果 head2 爲空,那麼直接返回 head1
            return head1
        elif head1.val > head2.val:  # 如果 head1 大於 head2 節點下的元素,那麼返回 head2 ,同時 head2 通過next指向下一個節點
            head2.next = self.mergeTwoLists(head1, head2.next)
            return head2
        else:  # 否則返回 head1 ,同時 head1 通過next指向下一個節點
            head1.next = self.mergeTwoLists(head1.next, head2)
            return head1

更多Python編程題,等你來挑戰:Python編程題彙總(持續更新中……)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章