Given the head of a singly linked list, swap every two adjacent nodes and return the new head.
Note: Try to swap the nodes, not only the data.
Examples:
Input :
Output : 2 -> 1 -> 4 -> 3 -> 5 Explanation: The list has 5 nodes, so we form pairs from the front: [1, 2], [3, 4], and 5 remains unpaired (odd node count). Swapping each pair gives: [2, 1], [4, 3], and 5 stays as is. Final list: 2 -> 1 -> 4 -> 3 -> 5.
Input :
Output : 7 -> 8 -> 2 -> 5 -> 1 Explanation: The list has 5 nodes, so we form pairs from the front: [8, 7], [5, 2], and 1 remains unpaired (odd node count). Swapping each pair gives: [7, 8], [2, 5], and 1 stays as is. Final list: 7 -> 8 -> 2 -> 5 -> 1.
[Naive Approach] - Swapping Data - O(n) Time and O(1) Space
Instead of changing the structure of the linked list, swap the data stored in every adjacent pair of nodes. Since only the values are exchanged, the links between nodes remain unchanged. This approach is simple and works well when swapping node data is inexpensive.
Start from the head and initialize curr = head.
Traverse the list while curr and curr->next are not NULL.
Swap the data of the current pair (curr->data and curr->next->data).
Move curr two nodes ahead to process the next pair.
Stop when fewer than two nodes remain.
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intval){data=val;next=nullptr;}};// Function to swap data of nodes in pairsNode*pairwiseSwap(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;}returnhead;}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 pairsstructNode*pairwiseSwap(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;}returnhead;}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
importjava.util.*;classNode{publicintdata;publicNodenext;publicNode(intval){data=val;next=null;}}publicclassMain{// Function to swap data of nodes in pairspublicstaticNodepairwiseSwap(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;}returnhead;}publicstaticvoidprintList(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.nextreturnheaddefprintList(head):temp=headwhiletempisnotNone:print(temp.data,end="")iftemp.nextisnotNone:print(" -> ",end="")temp=temp.nextprint()if__name__=='__main__':# Creating the linked list:# 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULLhead=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;publicclassNode{publicintdata;publicNodenext;publicNode(intval){data=val;next=null;}}publicclassProgram{// Function to swap data of nodes in pairspublicstaticNodepairwiseSwap(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;}returnhead;}publicstaticvoidprintList(Nodehead){Nodetemp=head;while(temp!=null){Console.Write(temp.data);if(temp.next!=null)Console.Write(" -> ");temp=temp.next;}Console.WriteLine();}publicstaticvoidMain(){// 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;}returnhead;}functionprintList(head){lettemp=head;while(temp!==null){process.stdout.write(temp.data.toString());if(temp.next!==null)process.stdout.write(" -> ");temp=temp.next;}console.log();}// Main executionlethead=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
[Expected Approach] - Changing Links - O(n) Time and O(1) Space
Instead of swapping the data inside nodes, swap the nodes themselves by updating their next pointers. This is more efficient when nodes store large or complex data, as only the links are modified while the node contents remain unchanged.
Handle the cases where the list has fewer than two nodes.
Initialize prev and curr to the first and second nodes of the current pair, and update head to curr.
For each pair, store the starting node of the next pair before modifying any links.
Reverse the link between the current pair by making curr->next point to prev.
If no more pairs remain (or only one node is left), connect the remaining node and stop.
Otherwise, connect the current swapped pair to the next swapped pair.
Move prev and curr to the next pair and repeat until all pairs are processed.
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);