Press "Enter" to skip to content

Swap Node Pairs

Ajk 0

Hello again everyone! Been sometime since I wrote here.

Today I wanted to take a peek at a simple Linked List problem – Swap Node Pairs. Took me a bout 5 mins to write it out so it should be a cup of tea!

Given a Linked List, we want to swap every two adjacent nodes and return the head. (i.e. given 1->2->3->4 we want to return 2->1->4->3). There is one tiny catch to it. To make sure we demonstrate our knowledge in pointers, we are going to try to use only constant space.

The first thing we need to do is make sure we remove any ambiguities. It is not specified whether in our Swap Node Pairs problem, the Linked List is a Singly Linked List or a Doubly Linked List. Hence we should absolutely ask in an interview situation. For the purpose of our solution we are going to assume our interviewer wants to know about a Doubly Linked List.

Below is the solution in Java:

Swap Node Pairs – Solution

There it is. Obviously our Swap Node Pairs solution runs in linear time (if you have problem calculating that, check some of my very first posts). Hope you guys enjoyed it… and I’ll see you guys next time ;D.

The following two tabs change content below.
If you like one of my posts the best way to support is give it a thumbs up, comment, or share it on social media 🙂