Merge Two Sorted Lists

LeetCode

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.

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
i
1
0
2
1
4
2
|
3
j
1
4
3
5
4
6
merged=[]
Step 1 / 7
Step 1:
Initialize dummy and tail. Compare list1[0] and list2[0].
Pointers: i=0, j=4
Focus: compare @ [0, 4]