Leetcode Algorithm Recursive Class - Merge Two Ordered Lists

Table of contents

21. Merge two sorted linked lists

answer:

code:


Merges two ascending lists into a new  ascending  list and returns. The new linked list is formed by splicing all the nodes of the given two linked lists. 

Example 1:

Input: l1 = [1,2,4], l2 = [1,3,4]
 Output: [1,1,2,3,4,4]

Example 2:

Input: l1 = [], l2 = []
 Output: []

Example 3:

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

hint:

  • The range of the number of nodes of the two linked lists is [0, 50]
  • -100 <= Node.val <= 100
  • l1 and  l2 both in  non-decreasing  order

 

answer:

First of all, we need to know: the function calls itself at runtime , this function is called a recursive function, and the calling process is called recursion

  • A recursive function must have a termination condition , otherwise an error will occur;
  • A recursive function calls itself continuously until it encounters a termination condition, backtracks, and finally returns the answer.

According to the rules of this topic:

  • Termination condition: When both linked lists are empty, it means that we have merged the linked lists.
  • Recursion: Determine which of the head nodes l1 and l2 is smaller, and then the next pointer of the smaller node points to the merged result of the remaining nodes (call recursion)

code:

class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1==null) return l2;
        if(l2==null) return l1;
        if(l1.val<l2.val){
            l1.next=mergeTwoLists(l1.next,l2);
            return l1;
        }else{
            l2.next=mergeTwoLists(l1,l2.next);
            return l2;
        }
    }
}

About return L1: We need to know that the core of recursion is to only focus on what this layer does and what to return. As for my next layer, I don’t need to worry about it.

Recursive process comprehension:

  1. If L1 is empty or L2 is empty, I just return L1 or L2
  2. If the first element of L1 is smaller than L2, put this element of L1 at the front, and don’t care about the latter, I just need to receive the result after the next level of recursive processing (let L1->next = the result of the next level) OK

 

Guess you like

Origin blog.csdn.net/qq_62799214/article/details/132205470