Friedrich Ewald My Personal Website

Leetcode: Merge two lists

class Solution:
  def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
    root = ListNode()
    current = root

    while list1 is not None and list2 is not None:
      if list1.val < list2.val:
        current.next = ListNode(list1.val)
        current = current.next
        list1 = list1.next
      else:
        current.next = ListNode(list2.val)
        current = current.next
        list2 = list2.next

    if list1 is not None:
      current.next = list1
    if list2 is not None:
      current.next = list2

    return root.next

Results

Runtime: 34 ms, faster than 97.81% of Python3 online submissions for Merge Two Sorted Lists. Memory Usage: 13.9 MB, less than 79.56% of Python3 online submissions for Merge Two Sorted Lists.


About the author

is an experienced Software Engineer with a Master's degree in Computer Science. He started this website in late 2015, mostly as a digital business card. He is interested in Go, Python, Ruby, SQL- and NoSQL-databases, machine learning and AI and is experienced in building scalable, distributed systems and micro-services at multiple larger and smaller companies.