将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var mergeTwoLists = function(l1, l2) {
let list = []
const toArr = (l) => {
if (!l) return
list.push(l.val)
if (l.next) {
toArr(l.next)
}
}
toArr(l1, list)
toArr(l2, list)
list = list.sort((a, b) => a - b)
const toListTree = (arr) => {
if (!arr.length) return null
return arr.reverse().reduce((next, val) => {
return { next, val }
}, null)
}
return toListTree(list)
};