# Pairwise swap elements of a given linked list by changing links?

827 views

Given a singly linked list, write a function to swap elements pairwise. For example, if the linked list is 1->2->3->4->5->6->7 then the function should change it to 2->1->4->3->6->5->7, and if the linked list is 1->2->3->4->5->6 then the function should change it to 2->1->4->3->6->5

posted Apr 21, 2014

Its simple you need to treat two nodes as one node and traverse.

``````struct node
{
int data;
struct node *next;
};
``````

Code to swap pairwise node

``````void pairWiseSwap(struct node **head)
{
// If linked list is empty or there is only one node in list
return;

// Initialize previous and current pointers

// Traverse the list
while (true)
{
struct node *next = curr->next;
curr->next = prev; // Change next of current as previous node

// If next NULL or next is the last node
if (next == NULL || next->next == NULL)
{
prev->next = next;
break;
}

// Change next of previous to next next
prev->next = next->next;

// Update previous and curr
prev = next;
curr = prev->next;
}
}
``````