merge-two-sorted-lists.js (1791B)
1 //Merge two sorted lists together and return the resulting singly linked list. 2 //The time complexity of this algorithm is O(n) where n is the length of both 3 //the lists combined. 4 //Runtime: 60ms Beats: 88.75% 5 //Memory: 44.1MB Beats: 54.16% 6 7 /** 8 * Definition for singly-linked list. 9 * function ListNode(val, next) { 10 * this.val = (val===undefined ? 0 : val) 11 * this.next = (next===undefined ? null : next) 12 * } 13 */ 14 /** 15 * @param {ListNode} list1 16 * @param {ListNode} list2 17 * @return {ListNode} 18 */ 19 var mergeTwoLists = function(list1, list2) { 20 21 22 23 if(list1 == null && list2 == null){ 24 return null; 25 } 26 if(list1 == null){ 27 return list2; 28 } 29 if(list2 == null){ 30 return list1; 31 } 32 const merged_list = new ListNode(); 33 var itr = merged_list; 34 var itr1 = new ListNode(); 35 while(list1 != null && list2 != null){ 36 itr1 = new ListNode(); 37 itr.next = itr1; 38 if(list1.val < list2.val){ 39 itr.val = list1.val; 40 list1 = list1.next; 41 } 42 else{ 43 itr.val = list2.val; 44 list2 = list2.next; 45 } 46 itr = itr1; 47 } 48 49 while(list1 != null){ 50 if(list1.next != null){ 51 itr1 = new ListNode(); 52 itr.next = itr1; 53 itr.val = list1.val; 54 list1 = list1.next; 55 itr = itr1; 56 } 57 else{ 58 itr.val = list1.val; 59 break; 60 } 61 } 62 while(list2 != null){ 63 if(list2.next != null){ 64 itr.next = itr1; 65 itr1 = new ListNode(); 66 itr.val = list2.val; 67 list2 = list2.next; 68 itr.next = itr1; 69 itr = itr1; 70 } 71 else{ 72 itr.val = list2.val; 73 break; 74 } 75 } 76 return merged_list; 77 };