Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
/** * 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) { var ans = [] while(l1 != null){ ans.push(new ListNode(l1.val));//cut ListNode and push into an array l1 = l1.next; } while(l2 != null){ ans.push(new ListNode(l2.val)); //cut ListNode and push into an array l2 = l2.next } ans.sort(function(a, b){ //sort the array return a.val - b.val; }) if(ans.length==0) return null; for(var i = 0; i < ans.length-1; i++){ ans[i].next = ans[i+1] } return ans[0] }; |