Monday, November 18, 2013

Pair swapping in a linked list

Given a singly linked list, we have to swap the adjacent nodes in it.

For example some input/output samples are given below

Input                              output
-------------------------------------------------
1->2->3->4->X                      2->1->4->3->X
1->2->3->4->5->X                   2->1->4->3->5->X
1->X                               1->X

The algorithm is very simple. We have to move pair by pair and swap the data part of each pair. 


Here is the C++ code for this.