Given a singly linked list with two values x and y, the task is to swap two nodes having values x and y without swapping data.
Examples:
Input: 1->2->3->4->5, x = 2, y = 4 Output: 1->4->3->2->5
Input: 10->15->12->13->20->14, x = 10, y = 20 Output: 20->15->12->13->10->14
Possible cases to handle:
When swapping 2 nodes, x and y, in a linked list, there are a few cases that can arise:
x and y are adjacent to each other, and
One of x or y is the head node of the list.
None of x or y is either a head node or a tail node.
x and y are not adjacent to each other, and:
One of x or y is the head node of the list.
None of x or y is either a head node or a tail node.
x or y don’t even exist in the linked list.
Therefore, our solution must handle all these cases.
[Naive Approach] By Keeping Track of Previous Node - O(n) Time and O(1) Space:
The idea is to first search x and y nodes in the given linked list. If any of them is not present, then return. While searching for x and y, keep track of current and previous pointers. First change next of previous pointers, then change next of current pointers.
Below is the diagram of the case where either Node X or Node Y is the head node of the list.
Swapping when Node X is the head of the List.
Below is the diagram of the case where Nodes X and Node Y are both not the head node of the list.
Swapping when neither Node X or Node Y is the head of the list.
Below is the implementation of the above approach:
C++
// C++ program to swap the nodes of a linked list rather// than swapping the data from the nodes.#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};// Function to swap nodes x and y in linked list by// changing links and return the updated head Node*swapNodes(Node*head,intx,inty){// Nothing to do if x and y are the sameif(x==y)returnhead;Node*prevX=nullptr,*currX=nullptr;Node*prevY=nullptr,*currY=nullptr;Node*curr=head;// First loop to find xwhile(curr!=nullptr){if(curr->data==x){currX=curr;break;}prevX=curr;curr=curr->next;}curr=head;// Second loop to find ywhile(curr!=nullptr){if(curr->data==y){currY=curr;break;}prevY=curr;curr=curr->next;}// If either x or y is not present, nothing to doif(currX==nullptr||currY==nullptr)returnhead;// If x is not head of the linked listif(prevX!=nullptr){prevX->next=currY;}else{head=currY;}// If y is not head of the linked listif(prevY!=nullptr){prevY->next=currX;}else{head=currX;}// Swap next pointersNode*temp=currY->next;currY->next=currX->next;currX->next=temp;returnhead;}voidprint(Node*curr){while(curr!=nullptr){cout<<curr->data<<" ";curr=curr->next;}cout<<endl;}intmain(){// Constructed linked list:// 1->2->3->4->5Node*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=swapNodes(head,4,3);print(head);return0;}
C
// C program to swap the nodes of a linked list rather// than swapping the data from the nodes.#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};// Function to swap nodes x and y in linked list by// changing links and return the updated head structNode*swapNodes(structNode*head,intx,inty){// Nothing to do if x and y are the sameif(x==y)returnhead;structNode*prevX=NULL,*currX=NULL;structNode*prevY=NULL,*currY=NULL;structNode*curr=head;// First loop to find xwhile(curr!=NULL){if(curr->data==x){currX=curr;break;}prevX=curr;curr=curr->next;}curr=head;// Second loop to find ywhile(curr!=NULL){if(curr->data==y){currY=curr;break;}prevY=curr;curr=curr->next;}// If either x or y is not present, nothing to doif(currX==NULL||currY==NULL)returnhead;// If x is not head of the linked listif(prevX!=NULL)prevX->next=currY;elsehead=currY;// If y is not head of the linked listif(prevY!=NULL)prevY->next=currX;elsehead=currX;// Swap next pointersstructNode*temp=currY->next;currY->next=currX->next;currX->next=temp;returnhead;}voidprint(structNode*curr){while(curr!=NULL){printf("%d ",curr->data);curr=curr->next;}printf("\n");}structNode*createNode(intx){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=x;node->next=NULL;returnnode;}intmain(){// Constructed linked list: 1->2->3->4->5structNode*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=swapNodes(head,4,3);print(head);return0;}
Java
// Java program to swap the nodes of a linked list rather// than swapping the data from the nodes.classNode{intdata;Nodenext;Node(intdata){this.data=data;this.next=null;}}classGfG{// Function to swap nodes x and y in linked list by changing linksstaticNodeswapNodes(Nodehead,intx,inty){// Nothing to do if x and y are the sameif(x==y){returnhead;}NodeprevX=null,currX=null;NodeprevY=null,currY=null;Nodecurr=head;// First loop to find xwhile(curr!=null){if(curr.data==x){currX=curr;break;}prevX=curr;curr=curr.next;}curr=head;// Second loop to find ywhile(curr!=null){if(curr.data==y){currY=curr;break;}prevY=curr;curr=curr.next;}// If either x or y is not present, nothing to doif(currX==null||currY==null){returnhead;}// If x is not head of the linked listif(prevX!=null){prevX.next=currY;}else{head=currY;}// If y is not head of the linked listif(prevY!=null){prevY.next=currX;}else{head=currX;}// Swap next pointersNodetemp=currY.next;currY.next=currX.next;currX.next=temp;returnhead;}staticvoidprintList(Nodecurr){while(curr!=null){System.out.print(curr.data+" ");curr=curr.next;}System.out.println();}publicstaticvoidmain(String[]args){// Constructed linked list: 1->2->3->4->5Nodehead=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=swapNodes(head,4,3);printList(head);}}
Python
# Python program to swap the nodes of a linked list rather# than swapping the data from the nodes.classNode:def__init__(self,data):self.data=dataself.next=None# Function to swap nodes x and y in linked# list by changing linksdefswapNodes(head,x,y):# Nothing to do if x and y are the sameifx==y:returnheadprevX=NonecurrX=headwhilecurrXandcurrX.data!=x:prevX=currXcurrX=currX.nextprevY=NonecurrY=headwhilecurrYandcurrY.data!=y:prevY=currYcurrY=currY.next# If either x or y is not present, nothing to doifcurrXisNoneorcurrYisNone:returnhead# If x is not head of the linked listifprevX:prevX.next=currYelse:head=currY# If y is not head of the linked listifprevY:prevY.next=currXelse:head=currX# Swap next pointerscurrX.next,currY.next=currY.next,currX.nextreturnheaddefprintList(curr):whilecurr:print(curr.data,end=" ")curr=curr.nextprint()if__name__=="__main__":# Constructed linked list: 1->2->3->4->5head=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=swapNodes(head,4,3)printList(head)
C#
// C# program to swap the nodes of a linked list rather// than swapping the data from the nodes.usingSystem;classNode{publicintdata;publicNodenext;publicNode(intdata){this.data=data;this.next=null;}}classGfG{// Function to swap nodes x and y in linked list by changing linksstaticNodeswapNodes(Nodehead,intx,inty){// Nothing to do if x and y are the sameif(x==y)returnhead;NodeprevX=null;NodecurrX=head;// Find currX and prevXwhile(currX!=null&&currX.data!=x){prevX=currX;currX=currX.next;}NodeprevY=null;NodecurrY=head;// Find currY and prevYwhile(currY!=null&&currY.data!=y){prevY=currY;currY=currY.next;}// If either x or y is not present, nothing to doif(currX==null||currY==null)returnhead;// If x is not head of the linked listif(prevX!=null)prevX.next=currY;elsehead=currY;// If y is not head of the linked listif(prevY!=null)prevY.next=currX;elsehead=currX;// Swap next pointersNodetemp=currY.next;currY.next=currX.next;currX.next=temp;returnhead;}staticvoidprintList(Nodecurr){while(curr!=null){Console.Write(curr.data+" ");curr=curr.next;}Console.WriteLine();}staticvoidMain(string[]args){// Constructed linked list: 1->2->3->4->5Nodehead=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=swapNodes(head,4,3);printList(head);}}
JavaScript
// Javascript program to swap the nodes of a linked list rather// than swapping the data from the nodes.classNode{constructor(data){this.data=data;this.next=null;}}// Function to swap nodes x and y in linked // list by changing linksfunctionswapNodes(head,x,y){// Nothing to do if x and y are the sameif(x===y)returnhead;letprevX=null,currX=head;// Find currX and prevXwhile(currX&&currX.data!==x){prevX=currX;currX=currX.next;}letprevY=null,currY=head;// Find currY and prevYwhile(currY&&currY.data!==y){prevY=currY;currY=currY.next;}// If either x or y is not present, nothing to doif(!currX||!currY)returnhead;// If x is not head of the linked listif(prevX)prevX.next=currY;elsehead=currY;// If y is not head of the linked listif(prevY)prevY.next=currX;elsehead=currX;// Swap next pointerslettemp=currY.next;currY.next=currX.next;currX.next=temp;returnhead;}functionprintList(curr){while(curr){console.log(curr.data+" ");curr=curr.next;}console.log();}// Constructed linked list:// 1->2->3->4->5lethead=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=swapNodes(head,4,3);printList(head);
Output
1 2 4 3 5
Time Complexity: O(n), where n is the number of nodes in linked list. Auxiliary Space: O(1)
[Efficient Approach] Using Single traversal - O(n) Time and O(1) Space:
The above code can be optimized to searchxandyin a single traversal. Two loops are used to keep the program simple.
Follow the steps below to solve the problem:
If x and y are the same, return as no need to swap.
Start traversing the List to search for x and y nodes by keeping track of the previous nodes prevX and prevY.
If either x or y is not found in the list, return without making any changes.
else, update connections:
If x is not the head, set prevX->next to currY. Otherwise, set currY as the new head.
If y is not the head, set prevY->next to currX. Otherwise, set currX as the new head.
Swap the next pointers of currX and currY to complete the swap.
Below is the implementation of the above approach:
C++
// C++ program to swaps the nodes of linked list rather// than swapping the data from the nodes.#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};// Function to swap nodes x and y in linked list by// changing links and return the updated head Node*swapNodes(Node*head,intx,inty){// Nothing to do if x and y are sameif(x==y)returnhead;Node*prevX=nullptr,*currX=nullptr;Node*prevY=nullptr,*currY=nullptr;Node*prev=nullptr,*curr=head;// Single loop to find both x and ywhile(curr!=nullptr){if(curr->data==x){prevX=prev;currX=curr;}elseif(curr->data==y){prevY=prev;currY=curr;}prev=curr;curr=curr->next;}// If either x or y is not present, nothing to doif(currX==nullptr||currY==nullptr)returnhead;// If x is not head of the linked listif(prevX!=nullptr)prevX->next=currY;else// Else make y the new headhead=currY;// If y is not head of the linked listif(prevY!=nullptr)prevY->next=currX;else// Else make x the new headhead=currX;// Swap next pointersNode*temp=currY->next;currY->next=currX->next;currX->next=temp;returnhead;}voidprint(Node*curr){while(curr!=nullptr){cout<<curr->data<<" ";curr=curr->next;}}intmain(){// Constructed linked list:// 1->2->3->4->5Node*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=swapNodes(head,4,3);print(head);return0;}
C
// C program to swaps the nodes of linked list rather// than swapping the data from the nodes.#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};// Function to swap nodes x and y in linked list by// changing links and return the updated head structNode*swapNodes(structNode*head,intx,inty){// Nothing to do if x and y are sameif(x==y)returnhead;structNode*prevX=NULL,*currX=NULL;structNode*prevY=NULL,*currY=NULL;structNode*prev=NULL,*curr=head;// Single loop to find both x and ywhile(curr!=NULL){if(curr->data==x){prevX=prev;currX=curr;}elseif(curr->data==y){prevY=prev;currY=curr;}prev=curr;curr=curr->next;}// If either x or y is not present, nothing to doif(currX==NULL||currY==NULL)returnhead;// If x is not head of the linked listif(prevX!=NULL)prevX->next=currY;elsehead=currY;// If y is not head of the linked listif(prevY!=NULL)prevY->next=currX;elsehead=currX;// Swap next pointersstructNode*temp=currY->next;currY->next=currX->next;currX->next=temp;returnhead;}voidprint(structNode*curr){while(curr!=NULL){printf("%d ",curr->data);curr=curr->next;}}structNode*createNode(intx){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=x;node->next=NULL;returnnode;}intmain(){// Constructed linked list:// 1->2->3->4->5structNode*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=swapNodes(head,4,3);print(head);return0;}
Java
// Java program to swaps the nodes of linked list rather// than swapping the data from the nodes.classNode{intdata;Nodenext;Node(intdata){this.data=data;this.next=null;}}classGfG{// Function to swap nodes x and y in linked list by// changing links and return the updated headstaticNodeswapNodes(Nodehead,intx,inty){// Nothing to do if x and y are sameif(x==y)returnhead;NodeprevX=null,currX=null;NodeprevY=null,currY=null;Nodeprev=null,curr=head;// Single loop to find both x and ywhile(curr!=null){if(curr.data==x){prevX=prev;currX=curr;}elseif(curr.data==y){prevY=prev;currY=curr;}prev=curr;curr=curr.next;}// If either x or y is not present, nothing to doif(currX==null||currY==null)returnhead;// If x is not head of the linked listif(prevX!=null)prevX.next=currY;else// Else make y the new headhead=currY;// If y is not head of the linked listif(prevY!=null)prevY.next=currX;else// Else make x the new headhead=currX;// Swap next pointersNodetemp=currY.next;currY.next=currX.next;currX.next=temp;returnhead;}staticvoidprintList(Nodecurr){while(curr!=null){System.out.print(curr.data+" ");curr=curr.next;}}publicstaticvoidmain(String[]args){// Constructed linked list:// 1->2->3->4->5Nodehead=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=swapNodes(head,4,3);printList(head);}}
Python
# Python program to swaps the nodes of linked list rather# han swapping the data from the nodes.classNode:def__init__(self,data):self.data=dataself.next=None# Function to swap nodes x and y in linked list by# changing links and return the updated head defswapNodes(head,x,y):# Nothing to do if x and y are sameifx==y:returnheadprevX=NonecurrX=NoneprevY=NonecurrY=Noneprev=Nonecurr=head# Single loop to find both x and ywhilecurr:ifcurr.data==x:prevX=prevcurrX=currelifcurr.data==y:prevY=prevcurrY=currprev=currcurr=curr.next# If either x or y is not present, nothing to doifcurrXisNoneorcurrYisNone:returnhead# If x is not head of the linked listifprevXisnotNone:prevX.next=currYelse:head=currY# If y is not head of the linked listifprevYisnotNone:prevY.next=currXelse:# Else make x the new headhead=currX# Swap next pointerstemp=currY.nextcurrY.next=currX.nextcurrX.next=tempreturnheaddefprintList(curr):whilecurr:print(curr.data,end=" ")curr=curr.nextif__name__=="__main__":# Constructed linked list:# 1->2->3->4->5head=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=swapNodes(head,4,3)printList(head)
C#
// C# program to swaps the nodes of linked list rather// than swapping the data from the nodes.usingSystem;classNode{publicintdata;publicNodenext;publicNode(intdata){this.data=data;this.next=null;}}classGfG{// Function to swap nodes x and y in linked list by// changing links and return the updated headstaticNodeswapNodes(Nodehead,intx,inty){// Nothing to do if x and y are sameif(x==y)returnhead;NodeprevX=null,currX=null;NodeprevY=null,currY=null;Nodeprev=null,curr=head;// Single loop to find both x and ywhile(curr!=null){if(curr.data==x){prevX=prev;currX=curr;}elseif(curr.data==y){prevY=prev;currY=curr;}prev=curr;curr=curr.next;}// If either x or y is not present, nothing to doif(currX==null||currY==null)returnhead;// If x is not head of the linked listif(prevX!=null)prevX.next=currY;else// Else make y the new headhead=currY;// If y is not head of the linked listif(prevY!=null)prevY.next=currX;else// Else make x the new headhead=currX;// Swap next pointersNodetemp=currY.next;currY.next=currX.next;currX.next=temp;returnhead;}staticvoidprintList(Nodecurr){while(curr!=null){Console.Write(curr.data+" ");curr=curr.next;}}staticvoidMain(string[]args){// Constructed linked list:// 1->2->3->4->5Nodehead=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=swapNodes(head,4,3);printList(head);}}
JavaScript
// Javascript program to swaps the nodes of linked list rather// than swapping the data from the nodes.classNode{constructor(data){this.data=data;this.next=null;}}// Function to swap nodes x and y in linked list by// changing links and return the updated head functionswapNodes(head,x,y){// Nothing to do if x and y are sameif(x===y)returnhead;letprevX=null,currX=null;letprevY=null,currY=null;letprev=null,curr=head;// Single loop to find both x and ywhile(curr){if(curr.data===x){prevX=prev;currX=curr;}elseif(curr.data===y){prevY=prev;currY=curr;}prev=curr;curr=curr.next;}// If either x or y is not present, nothing to doif(!currX||!currY)returnhead;// If x is not head of the linked listif(prevX)prevX.next=currY;elsehead=currY;// If y is not head of the linked listif(prevY)prevY.next=currX;elsehead=currX;// Swap next pointerslettemp=currY.next;currY.next=currX.next;currX.next=temp;returnhead;}functionprintList(curr){while(curr){console.log(curr.data+" ");curr=curr.next;}}// Constructed linked list:// 1->2->3->4->5lethead=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=swapNodes(head,4,3);printList(head);
Output
1 2 4 3 5
Time Complexity: O(n), where n is the number of nodes in linked list. Auxiliary Space: O(1)