Simple Java solution with explanation, 1ms


  • 4
    E

    It's my first post on leetcode to share my code. if I made any mistakes, please let me know. Thanks.

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;
        ListNode tmp;
        if (l1.val > l2.val) {
            tmp = l2;
            l2 = l1;
            l1 = tmp;
        }
        ListNode p = l1;
        while (l2 != null) {
            while (p.next != null && p.next.val <= l2.val) p = p.next;
            tmp = p.next;
            p.next = l2;
            l2 = tmp;
        }
        return l1;
    }
    

    Explanation:

    Starting from the list whose head's value is smaller, we use l1 to denote final list, l2 to point to a work list. Then recursively traverse l1 until we found an element larger than head value of l2 or reach the end of l1, then at this point, we switch the tail of l1 to l2, then continue to do the same until the working list l2 is empty. note that l2 is constantly changing, I just use it as a temporary pointer.
    In one sentence, just switch tail when you found p.next.val > l2.val.


Log in to reply
 

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