LeeCode21 merges two ordered linked lists (Java)

Topic link: LeeCode21 merges two ordered linked lists.
Topic description: When
Insert picture description here
comparing the heads of two linked lists, insert the smaller one into the result set. The time complexity is O(m+n). The idea is very good, but I wrote too much trouble.

class Solution {
    
    
    public    ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    
    
        if(l1==null&&l2==null){
    
    
            return null;
        }
        boolean flag=false;
        ListNode ans=new ListNode();
        if(l1!=null&&l2!=null){
    
    
            flag=true;
            if (l1.val > l2.val) {
    
    
                ans=l2;
                l2=l2.next;
            }else{
    
    
                ans=l1;
                l1=l1.next;
            }
        }


        ListNode temp=ans;
        if (l1 == null&&flag==false) {
    
    
            ans=l2;
            l2=l2.next;
            temp=ans;
            while (l2 != null) {
    
    
                temp.next=l2;
                l2=l2.next;
                temp=temp.next;
            }
            return ans;
        }
        if (l2 == null&&flag==false) {
    
    
            ans=l1;
            l1=l1.next;
            temp=ans;
            while (l1 != null) {
    
    
                temp.next=l1;
                l1=l1.next;
                temp=temp.next;
            }
            return ans;
        }
        while (l1 != null && l2 != null) {
    
    
            if (l1.val > l2.val) {
    
    
                temp.next=l2;
                l2=l2.next;
                temp=temp.next;
            }else{
    
    
                temp.next=l1;
                l1=l1.next;
                temp=temp.next;
            }
        }
        while(l1!=null){
    
    
            temp.next=l1;
            l1=l1.next;
            temp=temp.next;
        }
        while(l2!=null){
    
    
            temp.next=l2;
            l2=l2.next;
            temp=temp.next;
        }
        return ans;
    }
}

After the topic is over, look at the great god’s writing and worship on the spot. The idea is exactly the same, why is it so much worse?

class Solution {
    
    
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    
    
        ListNode prehead = new ListNode(-1);

        ListNode prev = prehead;
        while (l1 != null && l2 != null) {
    
    
            if (l1.val <= l2.val) {
    
    
                prev.next = l1;
                l1 = l1.next;
            } else {
    
    
                prev.next = l2;
                l2 = l2.next;
            }
            prev = prev.next;
        }

        // 合并后 l1 和 l2 最多只有一个还未被合并完,我们直接将链表末尾指向未合并完的链表即可
        prev.next = l1 == null ? l2 : l1;

        return prehead.next;
    }
}

Guess you like

Origin blog.csdn.net/weixin_43590593/article/details/112511170