Study Plan For Algorithms - Part12

WindMay發表於2024-08-26

1.合併 K 個升序連結串列
題目連結:https://leetcode.cn/problems/merge-k-sorted-lists/
給定一個連結串列陣列,每個連結串列都已經按升序排列。請將所有連結串列合併到一個升序連結串列中,返回合併後的連結串列。

class Solution:
    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
        import heapq

        dummy = ListNode()
        curr = dummy
        heap = []

        for i, lst in enumerate(lists):
            if lst:
                heapq.heappush(heap, (lst.val, i))

        while heap:
            val, index = heapq.heappop(heap)
            curr.next = ListNode(val)
            curr = curr.next

            if lists[index].next:
                lists[index] = lists[index].next
                heapq.heappush(heap, (lists[index].val, index))

        return dummy.next

2. 兩兩交換連結串列中的節點
題目連結:https://leetcode.cn/problems/swap-nodes-in-pairs/
給定一個連結串列,兩兩交換其中相鄰的節點,並返回交換後連結串列的頭節點。

class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        dummy = ListNode(0)
        dummy.next = head
        prev = dummy

        while head and head.next:
            first = head
            second = head.next

            prev.next = second
            first.next = second.next
            second.next = first

            prev = first
            head = first.next

        return dummy.next        

相關文章