本題連接 leetcode-cn.com/problems/me…
這道題是一道鏈表的題目,咱們能夠用遞歸來實現,直接貼代碼:bash
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var mergeTwoLists = function (l1, 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(l1, l2.next)
return l2
}
};
複製代碼
咱們用L1和L2表明兩個鏈表,遞歸的思路以下:ui
假設L1的長度爲m,L2的長度爲n,時間複雜度爲o(m + n)。this