leetcode21 Merge Two Sorted Lists combines two ordered lists into a new ordered list

Keywords: Java

Subject requirements

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

To translate it into a new ordered list, two ordered lists are combined into a new ordered list.

Idea 1: Circulation

When the nodes of the first two linked lists are non-empty, the smaller nodes are added to the result list and the next node of the smaller nodes is obtained. This compares until at least one list has been traversed. Add the remaining list to the end of the result list

public class MergeTwoSortedLists_21 {

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode start = new ListNode(0);
        ListNode temp = new ListNode(0);
        start.next = temp;
        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;
        }
        if(l1!=null){
            temp.next = l1;
        }
        if(l2!=null){
            temp.next = l2;
        }
        return start.next.next;
    }
    
    public class ListNode{
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }
}

Idea 2: Recursion

The smaller nodes of the two nodes are returned as a result of each comparison, and the smaller nodes are continued to be retrieved from the remaining list.

public class MergeTwoSortedLists_21 {
    public ListNode mergeTwoLists_recursive(ListNode l1, ListNode l2){
        if(l1==null){
            return l2;
        }else if (l2==null){
            return l1;
        }
        ListNode mergeHead;
        if(l1.val <= l2.val){
            mergeHead = l1;
            mergeHead.next = mergeTwoLists_recursive(l1.next, l2);
        }else{
            mergeHead = l2;
            mergeHead.next = mergeTwoLists(l1, l2.next);
        }
        return mergeHead;
    }
    
    public class ListNode{
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }
}

Posted by Duell on Tue, 12 Feb 2019 23:06:18 -0800