leetcode

Leetcode submissions
git clone git://git.laack.co/leetcode.git
Log | Files | Refs | README

merge-two-sorted-lists.py (1082B)


      1 # Definition for singly-linked list.
      2 # class ListNode:
      3 #     def __init__(self, val=0, next=None):
      4 #         self.val = val
      5 #         self.next = next
      6 class Solution:
      7     # len(list1, list2) can be 0
      8     def mergeTwoLists(
      9         self, list1: Optional[ListNode], list2: Optional[ListNode]
     10     ) -> Optional[ListNode]:
     11 
     12         if list1 is None:
     13             return list2
     14         if list2 is None:
     15             return list1
     16 
     17         head = None
     18 
     19         if list1.val < list2.val:
     20             head = list1
     21             list1 = list1.next
     22         else:
     23             head = list2
     24             list2 = list2.next
     25 
     26         assert head is not None
     27 
     28         current = head
     29 
     30         while list1 is not None and list2 is not None:
     31 
     32             if list1.val < list2.val:
     33                 current.next = list1
     34                 list1 = list1.next
     35             else:
     36                 current.next = list2
     37                 list2 = list2.next
     38 
     39             current = current.next
     40 
     41         if list1 is None:
     42             current.next = list2
     43         else:
     44             current.next = list1
     45 
     46         return head