1ms Java Solution, easy to understand


  • 3
    Y
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1==null||l2==null) return l1==null?l2:l1;
        ListNode head = null;
        if(l1.val<=l2.val) {
            head=l1;
            l1=l1.next;
        }
        else {
            head=l2;
            l2=l2.next;
        }
        ListNode temp = head;
        while(l1!=null&&l2!=null){
            if(l1.val<=l2.val) {
                temp.next=l1;
                l1=l1.next;
            }
            else {
                temp.next=l2;
                l2=l2.next;
            };
            temp=temp.next;
        }
        temp.next=l1==null?l2:l1;
        return head;
    }

  • 0
    M

    You don't really need to compare the head value l1 or l2 to determine the head of the merged list. You can just put a dummy head and start the merge right away, then return head.next to eliminate the dummy head.


Log in to reply
 

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