merge-two-sorted-lists.py
linked-lists/merge-two-sorted-lists.py · Python · 795 B · 2026-02-17 21:03
# Use a dummy head, then iterate through both lists, appending the smaller node to the merged list. Finally, append any remaining nodes from either list. # linked-lists from typing import Optional class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next # O(n + m) time | O(1) space def mergeTwoLists(list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: newhead = ListNode(-1, None) p1, p2 = list1, list2 curr = newhead while p1 and p2: if p1.val < p2.val: curr.next = p1 p1 = p1.next else: curr.next = p2 p2 = p2.next curr = curr.next if p1: curr.next = p1 elif p2: curr.next = p2 return newhead.next