21. Merge Two Sorted Lists
21. Merge Two Sorted Lists
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 * Definition for singly-linked list. 3 * function ListNode(val) { 4 * this.val = val; 5 * this.next = null; 6 * } 7 */ 8 /** 9 * @param {ListNode} l1 10 * @param {ListNode} l2 11 * @return {ListNode} 12 */ 13 var mergeTwoLists = function(l1, l2) { 14 15 //这题其实是归并排序的子问题 16 var newList = new ListNode(0); 17 var cur = newList; 18 var newNode =null; 19 20 21 while(l1&&l2){ 22 if(l1.val < l2.val){ 23 newNode = new ListNode(l1.val); 24 25 cur.next = newNode; 26 cur = cur.next; 27 28 l1 = l1.next; 29 30 }else{ 31 32 newNode = new ListNode(l2.val); 33 cur.next = newNode; 34 cur = cur.next; 35 l2 = l2.next; 36 } 37 } 38 39 while(l2){ 40 newNode = new ListNode(l2.val); 41 cur.next = newNode; 42 cur = cur.next; 43 l2 = l2.next; 44 } 45 46 while(l1){ 47 newNode = new ListNode(l1.val); 48 49 cur.next = newNode; 50 cur = cur.next; 51 52 l1 = l1.next; 53 } 54 55 56 return newList.next; 57 58 };