Skip to content

Merge Two Sorted Lists

LeetCode

01 · Question

You are given the heads of two sorted linked lists list1 and list2. Merge the two lists into one sorted list and return its head.

02 · Solution

Reference solution

1def mergeTwoLists(list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
2 dummy = ListNode(0)
3 tail = dummy
4
5 while list1 and list2:
6 if list1.val <= list2.val:
7 tail.next = list1
8 list1 = list1.next
9 else:
10 tail.next = list2
11 list2 = list2.next
12 tail = tail.next
13
14 tail.next = list1 if list1 else list2
15 return dummy.next