# Swap Nodes in Pairs in C++

Consider we have a linked list. We have to swap every two adjacent nodes and return its head. 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

## Example(C++)

Let us see the following implementation to get a better understanding −

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};
}

## Input

[1,2,3,4,5,6,7,8]

## Output

[2,1,4,3,6,5,8,7]

Updated on: 27-Apr-2020

563 Views 