/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode[]} lists * @return {ListNode} */ var mergeKLists = function(lists) { if (!lists || lists.length === 0) return null; let last = lists.length - 1; while (last != 0) { let i = 0; let j = last; while (i < j) { lists[i] = mergeTwoLists(lists[i++], lists[j--]); if (i >= j) last = j; } } return lists[0]; }; var mergeTwoLists = function(a, b) { if (a == null) return b; if (b === null) return a; let result = a; if (a.val <= b.val) { result.next = mergeTwoLists(a.next, b); } else { result = b; result.next = mergeTwoLists(a, b.next); } return result; };
Categories