LeetCode: Merge Two Sorted Lists Solution
(IMO) Not easy as categorizedApproach
Keep iteratate two pointers, one for each list
Append smaller node to the dummy node on each iteration
Implementation (iterative)
1var mergeTwoLists = function (l1, l2) {2 let dummy = (iter = new ListNode())34 while (l1 && l2) {5 if (l1.val < l2.val) {6 iter.next = l17 l1 = l1.next8 } else {9 iter.next = l210 l2 = l2.next11 }12 iter = iter.next13 }1415 // because the above loop stop when one of the list pointers is null16 // so this line is to make sure we don't miss the last pointer17 iter.next = l1 || l21819 return dummy.next20}
Implementation (recursive)
1var mergeTwoLists = function (l1, l2) {2 if (!l1) return l23 if (!l2) return l14 if (l1.val < l2.val) {5 l1.next = mergeTwoLists(l1.next, l2)6 return l17 } else {8 l2.next = mergeTwoLists(l1, l2.next)9 return l210 }11}
(Bonus) Implementation (break and rebuild)
Convert to arrays
Concat and sort
Build back to linked list
1var mergeTwoLists = function (l1, l2) {2 const llistToArray = llist => {3 let iter = llist4 const res = []5 while (iter) {6 res.push(iter.val)7 iter = iter.next8 }9 return res10 }11 const arrayToLlist = arr => {12 let dummy = (iter = new ListNode())13 arr.forEach(el => {14 const node = new ListNode(el)15 iter.next = node16 iter = iter.next17 })18 return dummy.next19 }2021 return arrayToLlist(22 [...llistToArray(l1), ...llistToArray(l2)].sort((a, b) => a - b)23 )24}
Comments
Loading comments...
Tags
leetcode
linked list
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
LeetCode: Add Two Numbers
Example of using dummy head technique
Previous Post
LeetCode: Odd Even Linked List
2 pointers running simultaneously