LeetCode question: 21 Merge two ordered linked lists

21Merge two ordered linked lists

        Title description

Merge the two ascending linked lists into a new Ascending linked list and return. The new linked list is formed by concatenating all the nodes of the two given linked lists. 

Example 1:

Import:l1 = [1,2,4], l2 = [1,3,4]
Exit:[1,1,2,3,4,4]

Example 2:

Import:l1 = [], l2 = []
Exit:[]

Example 3:

Import:l1 = [], l2 = [0]
Output:[0]

Question ideas:

1. Double pointer method:

Time complexity: O(M+N)

Define a new linked list, then define a temporary linked list, traverse the two linked lists, compare the values ​​​​of list1 and list2, and put the smaller one into the temporary linked list. At the same time, the smaller linked list has to go to the next linked list. Continue the next comparison between list1 and list2.

Illustration:

By analogy, if a certain linked list is traversed, then all the remaining linked lists that have not been traversed are put into tmp, and finally the head node of the tmp record is returned.

2. Recursive method:

Time complexity: O(M+N)

After we determine which node is smaller, we change the direction of the small linked list. Then we can see it as the merger of the two linked lists. Isn't this recursion?

As shown in the picture:

At this time, it is still necessary to merge the two ordered linked lists.

And so on

code demo

Double pointer method:

class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if(list1 == null) return list2;
        if(list2 == null) return list1;

        ListNode listnode = new ListNode();
        ListNode tmp = listnode;

        while(list1 != null && list2 != null) {
            if(list1.val <= list2.val) {
                tmp.next = list1;
                list1 = list1.next;
                tmp = tmp.next;
            } else {
                tmp.next = list2;
                list2 = list2.next;
                tmp = tmp.next;
            }
        }

        if(list1 != null) {
            tmp.next = list1;
        }
        if(list2 != null) {
            tmp.next = list2;
        }

        return listnode.next;
    }
}

Recursive method:

class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if(list1 == null) return list2;
        if(list2 == null) return list1;

        if(list1.val <= list2.val) {
            list1.next = mergeTwoLists(list1.next, list2);
            return list1;
        }

        list2.next = mergeTwoLists(list2.next, list1);
        return list2;
    }
}

Guess you like

Origin blog.csdn.net/cool_tao6/article/details/134210271