Merge Two Sorted Lists

Problem Id: 21 Difficulty: Easy Tag: Linked List Tag: Recursion


Intuition

Use an additional head note.

Solution


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        head = ListNode(None)
        current = head
        while l1 and l2:
            if l1.val < l2.val:
                current.next = l1
                current = current.next
                l1 = l1.next
                current.next = None
            else:
                current.next = l2
                current = current.next
                l2 = l2.next
                current.next = None

        if l1:
            current.next = l1
        else:
            current.next = l2
        return head.next