Start from head and initialize curr = head. Traverse while curr != NULL and curr->next != NULL.
Swap data of current pair (curr->data <-> curr->next->data).
Move to the next pair using curr = curr->next->next.
Stop when no pair remains
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intval){data=val;next=nullptr;}};// Function to swap data of nodes in pairsvoidpairwiseSwap(Node*head){Node*curr=head;// Traverse the list and swap data in pairswhile(curr!=nullptr&&curr->next!=nullptr){// Swap data of current node and the next nodeswap(curr->data,curr->next->data);// Move to the next paircurr=curr->next->next;}}voidprintList(Node*head){Node*temp=head;while(temp!=nullptr){cout<<temp->data;if(temp->next!=nullptr)cout<<" -> ";temp=temp->next;}cout<<endl;}intmain(){// Creating the linked list:// 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULLNode*head=newNode(1);head->next=newNode(2);head->next->next=newNode(3);head->next->next->next=newNode(4);head->next->next->next->next=newNode(5);head->next->next->next->next->next=newNode(6);pairwiseSwap(head);printList(head);return0;}
C
#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};// Function to swap data of nodes in pairsvoidpairwiseSwap(structNode*head){structNode*curr=head;// Traverse the list and swap data in pairswhile(curr!=NULL&&curr->next!=NULL){// Swap data of current node and the next nodeinttemp=curr->data;curr->data=curr->next->data;curr->next->data=temp;// Move to the next paircurr=curr->next->next;}}voidprintList(structNode*head){structNode*curr=head;while(curr!=NULL){printf("%d",curr->data);if(curr->next)printf(" -> ");curr=curr->next;}}structNode*createNode(intval){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=val;newNode->next=NULL;returnnewNode;}intmain(){// Creating the linked list: //1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULLstructNode*head=createNode(1);head->next=createNode(2);head->next->next=createNode(3);head->next->next->next=createNode(4);head->next->next->next->next=createNode(5);head->next->next->next->next->next=createNode(6);pairwiseSwap(head);printList(head);return0;}
Java
classNode{intdata;Nodenext;Node(intval){data=val;next=null;}}classGfG{// Function to swap data of nodes in pairsstaticvoidpairwiseSwap(Nodehead){Nodecurr=head;// Traverse the list and swap data in pairswhile(curr!=null&&curr.next!=null){// Swap data of current node and the next nodeinttemp=curr.data;curr.data=curr.next.data;curr.next.data=temp;// Move to the next paircurr=curr.next.next;}}staticvoidprintList(Nodehead){Nodetemp=head;while(temp!=null){System.out.print(temp.data);if(temp.next!=null){System.out.print(" -> ");}temp=temp.next;}System.out.println();}publicstaticvoidmain(String[]args){// Creating the linked list: // 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> nullNodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);head.next.next.next.next.next=newNode(6);pairwiseSwap(head);printList(head);}}
Python
classNode:def__init__(self,val):self.data=valself.next=None# Function to swap data of nodes in pairsdefpairwiseSwap(head):curr=head# Traverse the list and swap data in pairswhilecurrisnotNoneandcurr.nextisnotNone:# Swap data of current node and the next nodecurr.data,curr.next.data=curr.next.data,curr.data# Move to the next paircurr=curr.next.nextdefprintList(node):whilenodeisnotNone:print(f"{node.data}",end="")ifnode.nextisnotNone:print(" -> ",end="")node=node.nextprint()if__name__=="__main__":# Creating the linked list: # 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> Nonehead=Node(1)head.next=Node(2)head.next.next=Node(3)head.next.next.next=Node(4)head.next.next.next.next=Node(5)head.next.next.next.next.next=Node(6)pairwiseSwap(head)printList(head)
C#
usingSystem;classNode{publicintdata;publicNodenext;publicNode(intval){data=val;next=null;}}classGfG{// Function to swap data of nodes in pairspublicstaticvoidpairwiseSwap(Nodehead){Nodecurr=head;// Traverse the list and swap data in pairswhile(curr!=null&&curr.next!=null){// Swap data of current node and the next nodeinttemp=curr.data;curr.data=curr.next.data;curr.next.data=temp;// Move to the next paircurr=curr.next.next;}}staticvoidprintList(Nodehead){Nodetemp=head;while(temp!=null){Console.Write(temp.data+"");if(temp.next!=null)Console.Write(" -> ");temp=temp.next;}Console.WriteLine();}staticvoidMain(){// Creating the linked list:// 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> nullNodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);head.next.next.next.next.next=newNode(6);pairwiseSwap(head);printList(head);}}
JavaScript
classNode{constructor(val){this.data=val;this.next=null;}}// Function to swap data of nodes in pairsfunctionpairwiseSwap(head){letcurr=head;// Traverse the list and swap data in pairswhile(curr!==null&&curr.next!==null){// Swap data of current node and the next node[curr.data,curr.next.data]=[curr.next.data,curr.data];// Move to the next paircurr=curr.next.next;}}functionprintList(node){while(node!==null){process.stdout.write(node.data.toString());if(node.next!==null){process.stdout.write(" -> ");}node=node.next;}}// Driver Code// Creating the linked list: // 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> nulllethead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);head.next.next.next.next.next=newNode(6);pairwiseSwap(head);printList(head);
Output
2 -> 1 -> 4 -> 3 -> 6 -> 5
Changing Links - O(n) Time and O(1) Space
Instead of swapping the data inside nodes, we change the links (pointers) between nodes. This avoids heavy data movement, especially when nodes store complex objects (like student records).
We keep track of the previous node while traversing and change next of current to previous. We need ensure that proper pointers are set before the next iteration of the loop.
C++
#include<iostream>usingnamespacestd;// A linked list node structNode{intdata;Node*next;Node(intx){data=x;next=NULL;}};// Function to pairwise swap nodes Node*pairwiseSwap(Node*head){// Handle base cases if(head==NULL||head->next==NULL)returnhead;// Initialize pointers for // first node of pair and second node of pairNode*prev=head;Node*curr=head->next;// Update head to second node (after first swap)head=curr;// Traverse list in pairswhile(true){// Store next pair starting nodeNode*next=curr->next;// Perform swap of current paircurr->next=prev;// If no more pairs OR only one node leftif(next==NULL||next->next==NULL){// connect remaining node (if exists)prev->next=next;break;}// Connect current swapped pair to next swapped pairprev->next=next->next;// Move pointers to next pairprev=next;curr=prev->next;}// Step 10: Return new headreturnhead;}// Print in required format voidprintList(Node*node){while(node!=NULL){cout<<node->data;if(node->next!=NULL)cout<<" -> ";node=node->next;}}// Driver code intmain(){Node*head=newNode(1);head->next=newNode(2);head->next->next=newNode(3);head->next->next->next=newNode(4);head->next->next->next->next=newNode(5);head=pairwiseSwap(head);printList(head);return0;}
Java
importjava.io.*;// A linked list node classNode{intdata;Nodenext;Node(intx){data=x;next=null;}}publicclassMain{// Function to pairwise swap nodes staticNodepairwiseSwap(Nodehead){// Handle base cases if(head==null||head.next==null)returnhead;// Initialize pointers for // first node of pair and second node of pairNodeprev=head;Nodecurr=head.next;// Update head to second node (after first swap)head=curr;// Traverse list in pairswhile(true){// Store next pair starting nodeNodenext=curr.next;// Perform swap of current paircurr.next=prev;// If no more pairs OR only one node leftif(next==null||next.next==null){// connect remaining node (if exists)prev.next=next;break;}// Connect current swapped pair to next swapped pairprev.next=next.next;// Move pointers to next pairprev=next;curr=prev.next;}// Step 10: Return new headreturnhead;}// Print in required format staticvoidprintList(Nodenode){while(node!=null){System.out.print(node.data);if(node.next!=null)System.out.print(" -> ");node=node.next;}}// Driver code publicstaticvoidmain(String[]args){Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);head=pairwiseSwap(head);printList(head);}}
Python
# A linked list node classNode:def__init__(self,x):self.data=xself.next=None# Function to pairwise swap nodes defpairwiseSwap(head):# Handle base cases ifheadisNoneorhead.nextisNone:returnhead# Initialize pointers for # first node of pair and second node of pairprev=headcurr=head.next# Update head to second node (after first swap)head=curr# Traverse list in pairswhileTrue:# Store next pair starting nodenext_node=curr.next# Perform swap of current paircurr.next=prev# If no more pairs OR only one node leftifnext_nodeisNoneornext_node.nextisNone:# connect remaining node (if exists)prev.next=next_nodebreak# Connect current swapped pair to next swapped pairprev.next=next_node.next# Move pointers to next pairprev=next_nodecurr=prev.next# Step 10: Return new headreturnhead# Print in required format defprintList(node):whilenodeisnotNone:print(node.data,end="")ifnode.nextisnotNone:print(" -> ",end="")node=node.next# Driver code if__name__=="__main__":head=Node(1)head.next=Node(2)head.next.next=Node(3)head.next.next.next=Node(4)head.next.next.next.next=Node(5)head=pairwiseSwap(head)printList(head)
C#
usingSystem;// A linked list node publicclassNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}publicclassProgram{// Function to pairwise swap nodes publicstaticNodepairwiseSwap(Nodehead){// Handle base cases if(head==null||head.next==null)returnhead;// Initialize pointers for // first node of pair and second node of pairNodeprev=head;Nodecurr=head.next;// Update head to second node (after first swap)head=curr;// Traverse list in pairswhile(true){// Store next pair starting nodeNodenext=curr.next;// Perform swap of current paircurr.next=prev;// If no more pairs OR only one node leftif(next==null||next.next==null){// connect remaining node (if exists)prev.next=next;break;}// Connect current swapped pair to next swapped pairprev.next=next.next;// Move pointers to next pairprev=next;curr=prev.next;}// Step 10: Return new headreturnhead;}// Print in required format publicstaticvoidprintList(Nodenode){while(node!=null){Console.Write(node.data);if(node.next!=null)Console.Write(" -> ");node=node.next;}}// Driver code publicstaticvoidMain(){Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);head=pairwiseSwap(head);printList(head);}}
JavaScript
// A linked list node functionNode(x){this.data=x;this.next=null;}// Function to pairwise swap nodes functionpairwiseSwap(head){// Handle base cases if(head===null||head.next===null)returnhead;// Initialize pointers for // first node of pair and second node of pairletprev=head;letcurr=head.next;// Update head to second node (after first swap)head=curr;// Traverse list in pairswhile(true){// Store next pair starting nodeletnext=curr.next;// Perform swap of current paircurr.next=prev;// If no more pairs OR only one node leftif(next===null||next.next===null){// connect remaining node (if exists)prev.next=next;break;}// Connect current swapped pair to next swapped pairprev.next=next.next;// Move pointers to next pairprev=next;curr=prev.next;}// Step 10: Return new headreturnhead;}// Print in required format functionprintList(node){while(node!==null){process.stdout.write(node.data.toString());if(node.next!==null)process.stdout.write(" -> ");node=node.next;}}// Driver code lethead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);head=pairwiseSwap(head);printList(head);