Given a singly linked list, write a function to swap elements pairwise.
Read full article from Pairwise swap elements of a given linked list | GeeksforGeeks
void
pairWiseSwap(
struct
node *head)
{
struct
node *temp = head;
/* Traverse further only if there are at-least two nodes left */
while
(temp != NULL && temp->next != NULL)
{
/* Swap data of node with its next node's data */
swap(&temp->data, &temp->next->data);
/* Move temp by 2 for the next pair */
temp = temp->next->next;
}
}
METHOD 2 (Recursive)
void pairWiseSwap( struct node *head) { /* There must be at-least two nodes in the list */ if (head != NULL && head->next != NULL) { /* Swap the node's data with data of next node */ swap(&head->data, &head->next->data); /* Call pairWiseSwap() for rest of the list */ pairWiseSwap(head->next->next); } } |