Merge Two Sorted Lists in Python

class Solution:
    def mergeTwoLists(
        self, list1: Optional[ListNode], list2: Optional[ListNode]
    ) -> Optional[ListNode]:
        # Create a dummy node to simplify merging process
        dummy = ListNode()
        current = dummy

        # Iterate while both lists have elements
        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

        # Append the remaining elements of list1 or list2
        current.next = list1 if list1 is not None else list2

        # The merged list starts from dummy's next node
        return dummy.next

PrevNext