[Expected Approach - 1] Using Recursion- O(n) Time and O(n) Space
The idea is to swap the data of the first two adjacent nodes, then recursively move to the next pair of nodes. In each recursive call, the data of the current node is swapped with its next node, and the function continues to do so until there are fewer than two nodes left in the list.
Below is the implementation of the above approach:
C++
// C++ program to pairwise swap elements// in a given linked list#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intval){data=val;next=nullptr;}};// Recursive function to swap data of nodes in pairsvoidpairwiseSwap(Node*head){// Base case: if the list is empty or has only// one node, no swapif(head==nullptr||head->next==nullptr){return;}// Swap the data of the current node with the next nodeswap(head->data,head->next->data);// Recursion for the next pairpairwiseSwap(head->next->next);}voidprintList(Node*head){Node*curr=head;while(curr!=nullptr){cout<<curr->data<<" ";curr=curr->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
// C program to pairwise swap elements// in a given linked list#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};// Recursive function to swap data of nodes in pairsvoidpairwiseSwap(structNode*head){// Base case: if the list is empty or has// only one node, no swapif(head==NULL||head->next==NULL){return;}// Swap the data of the current node with the next nodeinttemp=head->data;head->data=head->next->data;head->next->data=temp;// Recursion for the next pairpairwiseSwap(head->next->next);}voidprintList(structNode*head){structNode*curr=head;while(curr!=NULL){printf("%d ",curr->data);curr=curr->next;}printf("\n");}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
// Java program to pairwise swap elements// in a given linked listclassNode{intdata;Nodenext;Node(intval){data=val;next=null;}}classGfG{// Recursive function to swap data of nodes in pairsstaticvoidpairwiseSwap(Nodehead){// Base case: if the list is empty or has // only one node, no swapif(head==null||head.next==null){return;}// Swap the data of the current node with the next nodeinttemp=head.data;head.data=head.next.data;head.next.data=temp;// Recursion for the next pairpairwiseSwap(head.next.next);}staticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){System.out.print(curr.data+" ");curr=curr.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
# Python program to pairwise swap elements# in a given linked listclassNode:def__init__(self,val):self.data=valself.next=None# Recursive function to swap data of nodes in pairsdefpairwiseSwap(head):# Base case: if the list is empty or # has only one node, no swapifheadisNoneorhead.nextisNone:return# Swap the data of the current node with the next nodehead.data,head.next.data=head.next.data,head.data# Recursion for the next pairpairwiseSwap(head.next.next)defprintList(head):curr=headwhilecurr:print(curr.data,end=" ")curr=curr.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#
// C# program to pairwise swap elements// in a given linked listusingSystem;classNode{publicintdata;publicNodenext;publicNode(intval){data=val;next=null;}}classGfG{// Recursive function to swap data of nodes in pairsstaticvoidpairwiseSwap(Nodehead){// Base case: if the list is empty or has // only one node, no swapif(head==null||head.next==null){return;}// Swap the data of the current node with // the next nodeinttemp=head.data;head.data=head.next.data;head.next.data=temp;// Recursion for the next pairpairwiseSwap(head.next.next);}staticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){Console.Write(curr.data+" ");curr=curr.next;}Console.WriteLine();}staticvoidMain(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);}}
JavaScript
// Javascript program to pairwise swap elements// in a given linked listclassNode{constructor(val){this.data=val;this.next=null;}}// Recursive function to swap data of nodes in pairsfunctionpairwiseSwap(head){// Base case: if the list is empty or// has only one node, no swapif(head===null||head.next===null){return;}// Swap the data of the current node with the next node[head.data,head.next.data]=[head.next.data,head.data];// Recursion for the next pairpairwiseSwap(head.next.next);}functionprintList(head){letcurr=head;while(curr!==null){console.log(curr.data+" ");curr=curr.next;}console.log();}// 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
Time complexity: O(n), where n is the number of nodes in the linked list. Auxiliary Space: O(n), recursive stack space.
[Expected Approach - 2] Using Iterative Method - O(n) Time and O(1) Space
The idea is to traverse the linked list from head and swap the data between adjacent nodes in pairs. Starting from the head node, we swap the data of the current node with the next node, then move two steps forward to swap the next pair.
Below is the implementation of the above approach:
C++
// C++ program to pairwise swap elements// in a given linked list#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*curr=head;while(curr!=nullptr){cout<<curr->data<<" ";curr=curr->next;}}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
// C program to pairwise swap elements// in a given linked list#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);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
// Java program to pairwise // swap elements of a linked listclassNode{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){Nodecurr=head;while(curr!=null){System.out.print(curr.data+" ");curr=curr.next;}}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
# Python program to swap the elements # of linked list pairwiseclassNode: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(head):curr=headwhilecurr:print(curr.data,end=" ")curr=curr.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#
// C# program to pairwise swap elements// of a linked listusingSystem;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){Nodecurr=head;while(curr!=null){Console.Write(curr.data+" ");curr=curr.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
// JavaScript program to pairwise swap // elements of a linked listclassNode{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(head){letcurr=head;while(curr!==null){console.log(curr.data);curr=curr.next;}}// 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
Time complexity: O(n), where n is the number of nodes in the linked list. Auxiliary Space: O(1)
[Expected Approach - 3] By Changing Links - O(n) Time and O(1) Space
The solution provided here swaps data of nodes. If the data contains many fields (for example a linked list of Student Objects), the swap operation will be costly. See the below article for a better solution that works well for all kind of linked lists
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.