This is the 12th day of my participation in the August More Text Challenge. For details, see:August is more challenging
The company’s old MAC reached the end of its useful life, replaced with a new one, and installed many software today. Yesterday, I just heard a MAC development efficiency sharing, and I found that I probably didn’t use a MAC before. But excellent software, there are many Windows computers at home, also regardless of the system, especially from Win10, if you do a willing heart, to learn and find some new software, will also let you use very cool. A word I heard last week: saturation attack. Although I have a particular aversion to Internet coinages and slang, it feels pretty graphic and doesn’t need to be explained. Only when we are liberated from a lot of simple and repetitive work can we launch a saturation attack on our areas of interest. After all, you have to waste time on things you love. As well as the exercise Flag set last week, this week has been three days, but it has not fallen, continue to adhere to, the body is the capital of revolution.
Back to the topic, continue to leetcode every day to do 1 problem, day arch a soldier, contribution, today is the 21st problem
The title
Merge the two ascending lists into a new ascending list and return. The new list is formed by concatenating all the nodes of the given two lists.
Example 1:
Input: l1 = [1,2,4], l2 = [1,3,4]
Output:,1,2,3,4,4 [1]
Example 2: Input: L1 = [], l2 = [] Output: []
Example 3: Input: L1 = [], l2 = [0] Output: [0]
Train of thought
Is also quite water, understand the meaning of the question, now 2 lists are from small to large order, need to merge, still maintain order. You can do it with a while loop, but it’s a lot of stuff, so you have to be careful whether the list is empty. Recursion is a more concise way to write, first of all to determine whether the two lists are free, free will return another; If none of them are empty, compare the head nodes and take the smaller one as the head node; Assuming that the head node of list 1 is relatively small, then the head node of recursively linked list 1 is the head node of the merged list, and the recursively linked list 1 removes the sub list and list 2 after the node of the merged list.
Java version code
/** * 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; } if (l1.val < l2.val) { l1.next = mergeTwoLists(l1.next, l2); return l1; } else { l2.next = mergeTwoLists(l1, l2.next); return l2; }}}Copy the code