Merge 2 sorted list intuitive solution

Iterative

class Solution:
    def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        if not l1:
            return l2
        if not l2:
            return l1
        if l2.val < l1.val:
            l1, l2 = l2, l1
        l1.next = self.mergeTwoLists(l1.next, l2)
        return l1

Tail-Recursive

class Solution:
    def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        head = ListNode()
        self._merge(head, l1, l2)
        return head.next

    def _merge(self, head: ListNode, l1: Optional[ListNode], l2: Optional[ListNode]):
        if not l1:
            head.next = l2
        elif not l2:
            head.next = l1
        else:
            if l1.val > l2.val:
                l1, l2 = l2, l1
            head.next = l1
            self._merge(l1, l1.next, l2)

Iterative

class Solution:
    def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        head = prev = ListNode()
        while l1 and l2:
            if l1.val > l2.val:
                l1, l2 = l2, l1
            prev.next = prev = l1
            l1 = l1.next
        prev.next = l1 or l2
        return head.next

Tail-Recursive2

How about this version of tail-recursion? is it smilar to iterative solution?

class Solution:
    def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        head = ListNode()
        return self._merge(head, head, l1, l2).next

    def _merge(self, head: ListNode, prev: ListNode, l1: Optional[ListNode], l2: Optional[ListNode]) -> ListNode:
        if l1 and l2:
            if l1.val > l2.val:
                l1, l2 = l2, l1
            prev.next = prev = l1
            return self._merge(head, prev, l1.next, l2)
        prev.next = l1 or l2
        return head
Comments (0)