题目:
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例 1:
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
示例 2:
输入:l1 = [], l2 = []
输出:[]
示例 3:
输入:l1 = [], l2 = [0]
输出:[0]
提示:
- 两个链表的节点数目范围是
[0, 50]
-100 <= Node.val <= 100
l1
和l2
均按 非递减顺序 排列
解题思路:
递归:使用递归需要明白递归三要素,参考@腐烂的橘子
1.终止条件:当l1或l2任意一个链表为空时
2.递归内容:如果l1.val < l2.val,则让 l1.next 去连接排序好后的链表头,如果l2.val <= l1.val,则让 l2.next 去连接排序好后的链表头(总之就是判断l1和l2那个的头结点更小,然后较小结点的next指向其余结点的合并结果)
3.返回值:每一层递归调用之后排序好后的头结点
举例:
1.
2.
3.
4.
5.
6.
7.
8.
java代码:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode() {} 7 * ListNode(int val) { this.val = val; } 8 * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 * } 10 */ 11 class Solution { 12 public ListNode mergeTwoLists(ListNode list1, ListNode list2) { 13 if(list1 == null){ 14 return list2; 15 }else if(list2 == null){ 16 return list1; 17 }else if(list1.val < list2.val){ 18 list1.next = mergeTwoLists(list1.next, list2); 19 return list1; 20 }else{ 21 list2.next = mergeTwoLists(list1, list2.next); 22 return list2; 23 } 24 25 } 26 }
python3代码:
1 # Definition for singly-linked list. 2 # class ListNode: 3 # def __init__(self, val=0, next=None): 4 # self.val = val 5 # self.next = next 6 class Solution: 7 def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: 8 if not list1: 9 return list2 10 if not list2: 11 return list1 12 13 if list1.val < list2.val: 14 list1.next = self.mergeTwoLists(list1.next, list2) 15 return list1 16 else: 17 list2.next = self.mergeTwoLists(list1, list2.next) 18 return list2 19 20标签:java,21,val,list1,list2,链表,ListNode,next From: https://www.cnblogs.com/liu-myu/p/16721844.html