LeetCode problem #24–Swap nodes in pairs (JavaScript)

  1. The node before the nodes being swapped must point to node 2
  2. Node 2 must now point to node 1
  3. Node 1 must now point to node 3

Solution #1: While loop

In this solution, we initialise a copy of the original LinkedList which we will use to traverse it, swapping as we go. We then run a while loop for so long as there remain 2 or more elements in the new LinkedList, as 2 are required in order to perform a swap.

Solution #2: Recursive

This approach is more or less identical to the while loop, but is slightly more concise. The performance differences between the two approaches in JavaScript are negligible.

--

--

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.