Aunt Guan is participating in the “Java Theme month – Java brush question clocking”, see the activity link for more details

First of all, I want to clarify that every algorithm problem has multiple solutions, and we’ll just talk about a few excellent solutions in LeetCode ~, hopefully

Can help you, that we first look at the topic description ~

I. Title Description:

Merges two ascending lists into a new ascending list and returns. A new list is formed by concatenating all the nodes of a given two lists. Example 1:

Input: l1 = 4-trichlorobenzene [1], l2 = [1 4] output:,1,2,3,4,4 [1] example 2: input: l1 = [], l2 = [] output: [] example 3: input: l1 = [], l2 = [0] output: [0]

Note: the number of nodes in both lists is [0, 50] -100 <= node. val <= 100, both L1 and L2 are sorted in non-decreasing order

Ii. Analysis of Ideas:

First of all, we know that L1 and L2 are both ascending linked lists, that is, the two lists are arranged from smallest to largest, so we only need to recursively compare the two top nodes to determine which one is in the first place. When the list is empty, the comparison is completed and the recursion exits.

Three, code implementation

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 = l1.next (l1.next, l2); return l1; Next = mergeTwoLists(l1, l2.next); next = mergeTwoLists(l1, l2.next); next = mergeTwoLists(l1, l2.next); return l2; }}Copy the code

Brush question summary

If you have other ideas to solve the problem, as long as you can achieve the requirements, it is no problem, all roads lead to Rome, not just limited to the solution I said ha ~, excellent ideas and code is more learning significance, let’s work together