leetcode problem - 21. Merge Two Sorted Lists

Title: Merge two sorted lists and return to the new list. The new list should be joined by the nodes of the two lists.

Example: Given a linked list
l1: 1->2->4,
l2: 1->3->4
Return list: 1 - > 1 - > 2 - > 3 - > 4 - > 4

Analysis: This is a simple question, but it takes me about forty minutes to do it. Because it feels that the size relationship between the two linked list nodes is not good. After I finished, I looked at the discuss ion, basically using recursion to do, I personally do not like using recursion, because the consumption of space is too large. Therefore, an easy-to-understand method based on cyclic iteration is written.

First, determine whether the next link of dummy is l1 or l2. For the above example, l1 >= l2, so dummy.next = l2, and l2 = l2.next.

Then a current node temp = dummy.next is used to straighten out the size relationship of each node in the two linked lists. At this time, l1 is the first node of the list 1, and l2 is the second node of the list 2. Comparing l1 = 1 < l2 = 3, therefore:
temp.next = l1; // The current node selects the smaller L1 in L1 and l2
temp = temp.next; // The current node moves one bit backwards
L1 = l1.next; //l1 moves one bit backwards

Then and Merge Two Sorted Array Also, note that the end of the node has not been processed.

public class Solution {
    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1 == null || l2 == null) return l1==null? l2:l1;
        ListNode dummy = new ListNode(0);
        if(l1.val < l2.val){
            dummy.next = l1;
            l1 = l1.next;
        }else{
            dummy.next = l2;
            l2 = l2.next;
        }
        ListNode temp = dummy.next;
        while(l1 != null  && l2 != null){
            if(l1.val < l2.val){
                temp.next = l1;
                temp = temp.next;
                l1 = l1.next;
            }else{
                temp.next = l2;
                temp = temp.next;
                l2 = l2.next;
            }
        }
        // Processing nodes with no comparative size at the tail
        temp.next = l1 == null ? l2:l1;
        return dummy.next;

    }
    public static void print(ListNode head){
        while(head != null){
            System.out.println(head.val);
            head = head.next;
        }

    }
    public static void main(String[] args) {
        ListNode l1 = new ListNode(4);
        ListNode l2 = new ListNode(5);
        ListNode l3 = new ListNode(6);
        ListNode l4 = new ListNode(1);
        ListNode l5 = new ListNode(2);
        ListNode l6 = new ListNode(3);

        l1.next = l2;
        l2.next = l3;
        l4.next = l5;
        l5.next = l6;

        print(mergeTwoLists(l1, l4));
    }
}

Posted by FUEL on Thu, 07 Feb 2019 17:42:17 -0800