Recursive answer


  • 0
    O
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode nHead;
        if (l1 == null && l2 == null) return l1;
        else if (l1 == null) return l2;
        else if (l2 == null) return l1;
        else {
            ListNode headL1 = l1;
            ListNode headL2 = l2;
            if (headL1.val < headL2.val) {
                nHead = headL1;
                nHead.next = mergeTwoLists(l1.next, l2);
            } else {
                nHead = headL2;
                nHead.next = mergeTwoLists(l1, l2.next);
            }
            return nHead;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.