My Java loop solution


  • 4
    V

    I know recursive is easy to understand, but I still try a clear loop method :)

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode fakeHead = new ListNode(0);
        ListNode current = fakeHead;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                current.next = l1;
                l1 = l1.next;
            } else {
                current.next = l2;
                l2 = l2.next;
            }
            current = current.next;
        }
        if (l1 == null) current.next = l2;
        if (l2 == null) current.next = l1;
        return fakeHead.next;
    }

  • 0
    J

    its not the solution......... you will ignore some elements


  • 0
    E

    change both if statements to while outside the first while loop and you should be all set


Log in to reply
 

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