示例 1:
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
示例 2:
输入:l1 = [], l2 = []
输出:[]
示例 3:
输入:l1 = [], l2 = [0]
输出:[0]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-two-sorted-lists
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路: 新建一个链表, 每次把val较小的节点加进来,并删除原链表的这个节点,一个链表为空时,把不为空的链表给加上
var mergeTwoLists = function(l1, l2) { if(l1 === null) { return l2 } if(l2 === null) { return l1 } let dammy = new ListNode() let cur = dammy while(l1 && l2) { if (l1.val > l2.val) { cur.next = l2 cur = cur.next l2 = l2.next } else { cur.next = l1 cur = cur.next l1 = l1.next } } cur.next = l1 === null ? l2 : l1 return dammy.next };
使用递归
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 } };