0021 - Merge Two Sorted Lists

大意

就是把已經排序的兩個 LinkedList 合併到一個 LinkedList,且要保持順序

實際作法

由於自己做出來都是 Timeout,應該是哪裡做錯了,以下附上正確的 Code:

# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution(object):
    def mergeTwoLists(self, list1, list2):
        """
        :type list1: Optional[ListNode]
        :type list2: Optional[ListNode]
        :rtype: Optional[ListNode]
        """
        
        head = ListNode()
        current = head

        while list1 != None and list2 != None:
            if list1.val <= list2.val:
                current.next = list1
                temp = list1.next
                current = list1
                list1 = temp
            else:
                current.next = list2
                temp = list2.next
                current = list2
                list2 = temp
        
        if list1 != None:
            current.next = list1
        if list2 != None:
            current.next = list2

        return head.next

建立一個新的 LIstNode 當作假的起頭(真正的起頭在假起頭的下一個),然後去比較兩個當前  ListNode 代表的數字

然後回傳假的起頭的下一個,就是排序好的 LinkedList!


Revision #2
Created 3 July 2024 08:19:17 by Nesquate
Updated 8 July 2024 03:17:52 by Nesquate