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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |