Given a linked list, pairwise swap its adjacent nodes. The swapping of data is not allowed, only links should be changed.

For example,

Input:  1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> NULL
 
Output: 2 —> 1 —> 4 —> 3 —> 6 —> 5 —> 8 —> 7 —> NULL

Practice this problem

The idea is to traverse the linked list, consider two nodes simultaneously, and swap their links. This looks simple enough but needs special attention while exchanging the links.

The algorithm can be implemented as follows in C, Java, and Python:

C


Download  Run Code

Output:

Before: 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> NULL
After : 2 —> 1 —> 4 —> 3 —> 6 —> 5 —> 8 —> 7 —> NULL

Java


Download  Run Code

Output:

Before : 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> null
After : 2 —> 1 —> 4 —> 3 —> 6 —> 5 —> 8 —> 7 —> null

Python


Download  Run Code

Output:

Before : 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> None
After : 2 —> 1 —> 4 —> 3 —> 6 —> 5 —> 8 —> 7 —> None

The time complexity of the above solution is O(n), where n is the total number of nodes in the linked list, and doesn’t require any extra space.

 
We can also write a recursive version of the above program. The idea remains the same, but here we pass the next pair information and the previous node through recursion.

C


Download  Run Code

Output:

Before: 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> NULL
After : 2 —> 1 —> 4 —> 3 —> 6 —> 5 —> 8 —> 7 —> NULL

Java


Download  Run Code

Output:

Before : 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> null
After : 2 —> 1 —> 4 —> 3 —> 6 —> 5 —> 8 —> 7 —> null

Python


Download  Run Code

Output:

Before : 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> None
After : 2 —> 1 —> 4 —> 3 —> 6 —> 5 —> 8 —> 7 —> None