/** * 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 && !l2) { returnnull } let array1 = listNodeToArray(l1) let array2 = listNodeToArray(l2) let array = array1.concat(array2) array.sort((a, b) => (a - b)) return arrayToListNode(array) };
functionlistNodeToArray (head) { let array = [] while (head) { array.push(head.val) head = head.next } return array }
functionarrayToListNode(array) { if(!array || !array.length) { returnnull } let node let head = new ListNode(array[0]) let pnode = head for(let i = 1; i < array.length; i++) { node = new ListNode(array[i]) pnode.next = node pnode = node } return head }