将两个有序链表合并为一个新的有序链表并返回。新链表是经过拼接给定的两个链表的全部节点组成的。 网络
示例:code
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4排序
来源:力扣(LeetCode)
连接:https://leetcode-cn.com/problems/merge-two-sorted-lists
著做权归领扣网络全部。商业转载请联系官方受权,非商业转载请注明出处。递归
递归三要素:leetcode
很好的图解参考连接:https://leetcode-cn.com/problems/merge-two-sorted-lists/solution/hua-jie-suan-fa-21-he-bing-liang-ge-you-xu-lian-bi/get
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ 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(l2.next, l1); return l2; } } }