Swap Nodes in Pairs in C++

C++Server Side ProgrammingProgramming

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 −

  • if head is not present, then return head
  • 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){
   ListNode *head = new ListNode(v[0]);
   for(int i = 1; i<v.size(); i++){
      ListNode *ptr = head;
      while(ptr->next != NULL){
         ptr = ptr->next;
      }
      ptr->next = new ListNode(v[i]);
   }
   return head;
}
void print_list(ListNode *head){
   ListNode *ptr = head;
   cout << "[";
   while(ptr->next){
      cout << ptr->val << ", ";
      ptr = ptr->next;
   }
   cout << "]" << endl;
}
class Solution {
public:
   ListNode* swapPairs(ListNode* head) {
      if(!head)return head;
      ListNode* first= head;
      ListNode* second = head->next;
      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};
   ListNode *head = make_list(v);
   print_list(ob.swapPairs(head));
}

Input

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

Output

[2,1,4,3,6,5,8,7]
raja
Published on 30-Jan-2020 15:14:03
Advertisements