JAVA Easy to understand solution


  • 10
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode ans = new ListNode(0);
        ListNode prev = ans;
        while(l1 != null && l2 != null){
            if(l1.val > l2.val){
                prev.next = l2;
                l2 = l2.next;
            } else{
                prev.next = l1;
                l1 = l1.next;
            }
            prev = prev.next;
        }
        if(l2 == null){
            prev.next = l1;
        } else {
            prev.next = l2;
        }
        return ans.next;
    }

  • 0
    C

    Brilliant use of "prev"!


  • 2

    why use prev.next in last line?


  • 0
    H

    Thanks a lot for your iteration version!
    Based on your solution, I made the following implementation, which is more lengthy than yours, but maybe easier to understand for some people. Thank you again!

    public ListNode mergeTwoLists(ListNode l1, ListNode l2)
    {
        if (l1 == null)
            return l2;
        if (l2 == null)
            return l1;
        
        ListNode head = null;
        if (l1.val >= l2.val)
        {
            head = l2;
            l2 = l2.next;
        }
        else // l1.val < l2.val
        {
            head = l1;
            l1 = l1.next;
        }
        
        ListNode curNode = head;
        while (l1 != null && l2 != null)
        {
            if (l1.val >= l2.val)
            {
                curNode.next = l2;
                l2 = l2.next;
            }
            else // l1.val < l2.val
            {
                curNode.next = l1;
                l1 = l1.next;
            }
            curNode = curNode.next;
        }
        if (l1 == null)
            curNode.next = l2;
        else if (l2 == null)
            curNode.next = l1;
            
        return head;
    }

  • 0
    2
    This post is deleted!

  • 0
    Y

    @Harrywithcode the last line is ans.next where ans is a dummy pointer. It points to the new head of the merged sorted list.


Log in to reply
 

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