Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.
Iterative Approach
dummy
node to simplify the code by avoiding edge cases when appending nodes.current
to point to the current node in the merged list, starting from dummy
.list1
and list2
are not None
:
list1
and list2
.current.next
and move current
to current.next
.list1
or list2
forward depending on which node was appended.list1
or list2
to the end of the merged list.dummy.next
, which points to the head of the merged sorted list.list1
and list2
, respectively. We iterate through each list once.class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(0)
current = dummy
while list1 and list2:
if list1.val <= list2.val:
current.next = list1
list1 = list1.next
else:
current.next = list2
list2 = list2.next
current = current.next
if list1:
current.next = list1
elif list2:
current.next = list2
return dummy.next