Pairwise swap elements of a given linked list using C++ program

Pairwise swap elements of a linked list: In this article, we will learn how to implement pairwise swap elements of a given linked list using the C++ program? By Souvik Saha Last updated : August 01, 2023

Problem statement

Given a linked list, write a C++ program to implement pairwise swap elements of the given linked list.

Consider the below example with sample input and output:

```If a linked list is 1 → 2 → 3 → 4 → 5
Then the output will be: 2 → 1 → 4 → 3 → 5
If the linked list is 1 → 2 → 3 → 4 → 5 → 6
Then the output will be: 2 → 1 → 4 → 3 → 6 → 5
```

Algorithm

To solve this problem we firstly iterate the list from the head and take two consecutive nodes from that and swap the key values of them. Go for next two consecutive nodes. If there is only one node left then keep it same.

```while (curr is not NULL  &&curr->next is not NULL)
temp=curr->data;
curr->data=curr->next->data;
curr->next->data=temp;
curr=curr->next->next;
End While
```

Pairwise swap elements of a given linked list using C++ program

```#include <bits/stdc++.h>
using namespace std;

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

//Create a new node
struct node* create_node(int x)
{
struct node* temp = new node;
temp->data = x;
temp->next = NULL;
return temp;
}

//Enter the node into the linked list
{
struct node* store = create_node(x);
return;
}
while (temp->next) {
temp = temp->next;
}
temp->next = store;
}

{
return NULL;
}
while (curr && curr->next) {
int temp = curr->data;
curr->data = curr->next->data;
curr->next->data = temp;
curr = curr->next->next;
}
}

//Print the list
{
while (temp) {
cout << temp->data << " ";
temp = temp->next;
}
}

int main()
{
struct node* l = NULL;

push(&l, 1);
push(&l, 2);
push(&l, 3);
push(&l, 4);
push(&l, 5);
push(&l, 6);

cout << "Before the swap operation" << endl;
print(l);

l = swap(l);

cout << "\nAfter the swap operation" << endl;
print(l);

return 0;
}
```

Output

```Before the swap operation
1 2 3 4 5 6
After the swap operation
2 1 4 3 6 5
```