[Algorithm-Java implementation] Merging two ordered linked lists

[Algorithm-Java implementation] Merging two ordered linked lists

1. Problem description:

The two merged into a new list in ascending order of ascending list and returns. The new linked list is composed by splicing all the nodes of the given two linked lists.

2. Question answer:

method:Recursion

If l1 or l2 is an empty linked list from the beginning, then there is no operation to merge, so we only need to return a non-empty linked list. Otherwise, we have to determine which of the head nodes of the linked list of l1 and l2 has the smaller value, and then recursively decide the next node to be added to the result. If one of the two linked lists is empty, the recursion ends.
Analysis of this question: Leetcode21

I think it’s easier to understand: drawing solution algorithm

3. Algorithm analysis:

1. The time complexity is O(n+m). This problem needs to judge all the nodes of the two linked lists, and the time complexity depends on the number of nodes of the two linked lists.

2. The extra space complexity is O(n+m). The essence of recursion is to call the computer stack. The size of the stack depends on the depth of the recursive call (the depth is the number of nodes in the two linked lists).

3.Recursion: Recursion means calling itself when the program is running, and a recursive process is the process of stacking.

When using recursion, you should consider 1. How to design a recursive function 2. The termination condition of recursion

code show as below


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    
    
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    
    
        if(l1==null){
    
    
            return l2;
        }else if(l2==null){
    
    
            return l1;
        }else if(l1.val<l2.val){
    
    
            l1.next=mergeTwoLists(l1.next,l2);
            return l1;
        }else {
    
    
            l2.next=mergeTwoLists(l1,l2.next);
            return l2;
        }
    }
}

Guess you like

Origin blog.csdn.net/hkdhkdhkd/article/details/109195885