Question: Given two sorted linked lists, merge them!
eg:
List 1 : 1 -> 3 -> 5 List 2 : 2 -> 4 -> 6 Merged list: 1 -> 2 -> 3 -> 4 -> 5 -> 6
If you've solved merge sort before, the approach is similar to that but here we have to play pointers. So let's play with them!
Algorithm :
var mergeTwoLists = function(l1, l2) { let dummy = new ListNode(-1); let head = dummy; while(l1!= null && l2 != null){ if(l1.val<l2.val){ head.next = l1; l1 = l1.next; }else{ head.next = l2; l2 = l2.next; } head = head.next; } if(l1 != null){ head.next = l1; } if(l2 != null){ head.next = l2; } return dummy.next; };
That's it!
Top comments (0)