# Program to swap nodes of a linked list pair wise in C++

Suppose we have a linked list. We have to swap every two adjacent nodes (pair) and return its head. Here the constraint is that, we cannot modify the value of the nodes, only the node itself can be changed. So if the list is like [1,2,3,4], then the resultant list will be [2,1,4,3].

To solve this, we will follow these steps −

• first := head, second := next of head, dummy is one new node with value -1
• next of dummy := first, and prev := dummy
• while second is not null
• temp := next of second
• next of first := next of second
• next of second := first
• next of prev := second
• prev := first
• if temp is not null, then first := temp and second := next of temp, otherwise break
• return next of dummy

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class ListNode{
public:
int val;
ListNode *next;
ListNode(int data){
val = data;
next = NULL;
}
};
ListNode *make_list(vector<int> v){
for(int i = 1; i<v.size(); i++){
while(ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = new ListNode(v[i]);
}
}
cout << "[";
while(ptr->next){
cout << ptr->val << ", ";
ptr = ptr->next;
}
cout << "]" << endl;
}
class Solution {
public:
ListNode* dummy = new ListNode(-1);
dummy->next = first;
ListNode* prev = dummy;
while(second){
ListNode* temp = second->next;
first->next = second->next;
second->next = first;
prev->next = second;
prev = first;
if(temp){
first = temp;
second = temp ->next;
}
else break;
}
return dummy->next;
}
};
main(){
Solution ob;
vector<int> v = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
}

## Input

{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}

## Output

[2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13,]

Updated on: 20-Oct-2020

117 Views 