PracticeNeetCode ↗LeetCode ↗
Given the heads of two sorted linked lists, merge them into a single sorted list and return its head.
tail pointer starting at dummy.tail.next, advance that list's pointer and tail.tail.next.dummy.next as the merged list's head.Time: O(n + m) — Space: O(1)
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def mergeTwoLists(list1: ListNode | None, list2: ListNode | None) -> ListNode | None:
dummy = ListNode()
tail = dummy
while list1 and list2:
if list1.val <= list2.val:
tail.next = list1
list1 = list1.next
else:
tail.next = list2
list2 = list2.next
tail = tail.next
tail.next = list1 if list1 else list2
return dummy.nextHow the solution above works, piece by piece.
dummy is a placeholder node before the real head, so the first node doesn't need a special case. tail is the end of the merged list so far.tail.tail forward.tail.next = list1 if list1 else list2.dummy.next. No new nodes are created, only pointers are relinked: O(m + n) time, O(1) space.Running it on list1 = [1, 2, 4], list2 = [1, 3, 4]:
tail. On a tie (1 and 1, 4 and 4) <= takes list1 first. When list2 runs out, the rest of list1 (the last 4) is attached in one go.