將兩個有序鏈表合併爲一個新的有序鏈表並返回。新鏈表是經過拼接給定的兩個鏈表的全部節點組成的。 網絡
示例: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; } } }