Close

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.

#include <iostream>
using namespace std;
struct Node
{
int data;
Node * next;
};
void Print(Node * head)
{
while ( head )
{
cout<< head->data << " ";
head = head->next;
}
cout << endl;
}
Node * Insert(Node * head, int d )
{
Node * newNode = new Node();
newNode->data = d;
newNode->next = head;
return newNode;
}
Node * PairSwap(Node * head)
{
if( head == NULL || head->next == NULL )
return head;
Node * first = head;
Node * second = first->next;
while ( first != NULL && second != NULL )
{
//swap data
int temp = first->data;
first->data = second->data;
second->data = temp;
//move to next pair
first = second->next;
if( first != NULL )
{
second = first->next;
}
}
return head;
}
int main()
{
Node * head = NULL;
head = Insert(head, 5);
head = Insert(head, 4);
head = Insert(head, 3);
head = Insert(head, 2);
head = Insert(head, 1);
Print(head);
head = PairSwap(head);
Print(head);
Node * head1 = NULL;
head1 = Insert(head1, 6);
head1 = Insert(head1, 5);
head1 = Insert(head1, 4);
head1 = Insert(head1, 3);
head1 = Insert(head1, 2);
head1 = Insert(head1, 1);
Print(head1);
head1 = PairSwap(head1);
Print(head1);
return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *