LeetCode problem #21–Merge two sorted lists (JavaScript)

Solution #1: While loop

In this fairly classic approach to a comparison question, we start by creating a while loop. This loop will run for as long as both LinkedLists contain a node, and in each iteration will compare the two available nodes, take the lower one, and finally move that LinkedList along to its next entry.

Solution #2: Recursion

LeetCode user yangliguang posted a great recursion approach, which I have expanded upon below. It does essentially the same thing as the while loop, but in a much more concise way. It can actually be simplified to just 4 lines, but of course that’s only at the expense of some readability.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Duncan McArdle

Duncan McArdle


Full-stack software developer from the UK, author of the Aftermath book series, full time tech-nerd.