Given a singly linked list with two value x and y, the task is to swap two nodes having values x and y without swapping data.

Swap nodes in a linked list without swapping data
Examples:
Input: 10->15->12->13->20->14, x = 12, y = 20
Output: 10->15->20->13->12->14
Input: 10->15->12->13->20->14, x = 10, y = 20
Output: 20->15->12->13->10->14
Input: 10->15->12->13->20->14, x = 12, y = 13
Output: 10->15->13->12->20->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:
The idea is to first search x and y 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 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++
#include <bits/stdc++.h>
using namespace std;
class Node {
public :
int data;
Node* next;
};
void swapNodes(Node** head_ref, int x, int y)
{
if (x == y)
return ;
Node *prevX = NULL, *currX = *head_ref;
while (currX && currX->data != x) {
prevX = currX;
currX = currX->next;
}
Node *prevY = NULL, *currY = *head_ref;
while (currY && currY->data != y) {
prevY = currY;
currY = currY->next;
}
if (currX == NULL || currY == NULL)
return ;
if (prevX != NULL)
prevX->next = currY;
else
*head_ref = currY;
if (prevY != NULL)
prevY->next = currX;
else
*head_ref = currX;
Node* temp = currY->next;
currY->next = currX->next;
currX->next = temp;
}
void push(Node** head_ref, int new_data)
{
Node* new_node = new Node();
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList(Node* node)
{
while (node != NULL) {
cout << node->data << " " ;
node = node->next;
}
}
int main()
{
Node* start = NULL;
push(&start, 7);
push(&start, 6);
push(&start, 5);
push(&start, 4);
push(&start, 3);
push(&start, 2);
push(&start, 1);
cout << "Linked list before calling swapNodes() " ;
printList(start);
swapNodes(&start, 4, 3);
cout << "\nLinked list after calling swapNodes() " ;
printList(start);
return 0;
}
|
C
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void swapNodes( struct Node** head_ref, int x, int y)
{
if (x == y)
return ;
struct Node *prevX = NULL, *currX = *head_ref;
while (currX && currX->data != x) {
prevX = currX;
currX = currX->next;
}
struct Node *prevY = NULL, *currY = *head_ref;
while (currY && currY->data != y) {
prevY = currY;
currY = currY->next;
}
if (currX == NULL || currY == NULL)
return ;
if (prevX != NULL)
prevX->next = currY;
else
*head_ref = currY;
if (prevY != NULL)
prevY->next = currX;
else
*head_ref = currX;
struct Node* temp = currY->next;
currY->next = currX->next;
currX->next = temp;
}
void push( struct Node** head_ref, int new_data)
{
struct Node* new_node
= ( struct Node*) malloc ( sizeof ( struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList( struct Node* node)
{
while (node != NULL) {
printf ( "%d " , node->data);
node = node->next;
}
}
int main()
{
struct Node* start = NULL;
push(&start, 7);
push(&start, 6);
push(&start, 5);
push(&start, 4);
push(&start, 3);
push(&start, 2);
push(&start, 1);
printf ( "\n Linked list before calling swapNodes() " );
printList(start);
swapNodes(&start, 4, 3);
printf ( "\n Linked list after calling swapNodes() " );
printList(start);
return 0;
}
|
Java
class Node {
int data;
Node next;
Node( int d)
{
data = d;
next = null ;
}
}
class LinkedList {
Node head;
public void swapNodes( int x, int y)
{
if (x == y)
return ;
Node prevX = null , currX = head;
while (currX != null && currX.data != x) {
prevX = currX;
currX = currX.next;
}
Node prevY = null , currY = head;
while (currY != null && currY.data != y) {
prevY = currY;
currY = currY.next;
}
if (currX == null || currY == null )
return ;
if (prevX != null )
prevX.next = currY;
else
head = currY;
if (prevY != null )
prevY.next = currX;
else
head = currX;
Node temp = currX.next;
currX.next = currY.next;
currY.next = temp;
}
public void push( int new_data)
{
Node new_Node = new Node(new_data);
new_Node.next = head;
head = new_Node;
}
public void printList()
{
Node tNode = head;
while (tNode != null ) {
System.out.print(tNode.data + " " );
tNode = tNode.next;
}
}
public static void main(String[] args)
{
LinkedList llist = new LinkedList();
llist.push( 7 );
llist.push( 6 );
llist.push( 5 );
llist.push( 4 );
llist.push( 3 );
llist.push( 2 );
llist.push( 1 );
System.out.print(
"\n Linked list before calling swapNodes() " );
llist.printList();
llist.swapNodes( 4 , 3 );
System.out.print(
"\n Linked list after calling swapNodes() " );
llist.printList();
}
}
|
Python
class LinkedList( object ):
def __init__( self ):
self .head = None
class Node( object ):
def __init__( self , d):
self .data = d
self . next = None
def swapNodes( self , x, y):
if x = = y:
return
prevX = None
currX = self .head
while currX ! = None and currX.data ! = x:
prevX = currX
currX = currX. next
prevY = None
currY = self .head
while currY ! = None and currY.data ! = y:
prevY = currY
currY = currY. next
if currX = = None or currY = = None :
return
if prevX ! = None :
prevX. next = currY
else :
self .head = currY
if prevY ! = None :
prevY. next = currX
else :
self .head = currX
temp = currX. next
currX. next = currY. next
currY. next = temp
def push( self , new_data):
new_Node = self .Node(new_data)
new_Node. next = self .head
self .head = new_Node
def printList( self ):
tNode = self .head
while tNode ! = None :
print tNode.data,
tNode = tNode. next
llist = LinkedList()
llist.push( 7 )
llist.push( 6 )
llist.push( 5 )
llist.push( 4 )
llist.push( 3 )
llist.push( 2 )
llist.push( 1 )
print "Linked list before calling swapNodes() "
llist.printList()
llist.swapNodes( 4 , 3 )
print "\nLinked list after calling swapNodes() "
llist.printList()
|
C#
using System;
class Node {
public int data;
public Node next;
public Node( int d)
{
data = d;
next = null ;
}
}
public class LinkedList {
Node head;
public void swapNodes( int x, int y)
{
if (x == y)
return ;
Node prevX = null , currX = head;
while (currX != null && currX.data != x) {
prevX = currX;
currX = currX.next;
}
Node prevY = null , currY = head;
while (currY != null && currY.data != y) {
prevY = currY;
currY = currY.next;
}
if (currX == null || currY == null )
return ;
if (prevX != null )
prevX.next = currY;
else
head = currY;
if (prevY != null )
prevY.next = currX;
else
head = currX;
Node temp = currX.next;
currX.next = currY.next;
currY.next = temp;
}
public void push( int new_data)
{
Node new_Node = new Node(new_data);
new_Node.next = head;
head = new_Node;
}
public void printList()
{
Node tNode = head;
while (tNode != null ) {
Console.Write(tNode.data + " " );
tNode = tNode.next;
}
}
public static void Main(String[] args)
{
LinkedList llist = new LinkedList();
llist.push(7);
llist.push(6);
llist.push(5);
llist.push(4);
llist.push(3);
llist.push(2);
llist.push(1);
Console.Write(
"\n Linked list before calling swapNodes() " );
llist.printList();
llist.swapNodes(4, 3);
Console.Write(
"\n Linked list after calling swapNodes() " );
llist.printList();
}
}
|
Javascript
<script>
class Node {
constructor(val) {
this .data = val;
this .next = null ;
}
}
var head;
function swapNodes(x , y) {
if (x == y)
return ;
var prevX = null , currX = head;
while (currX != null && currX.data != x) {
prevX = currX;
currX = currX.next;
}
var prevY = null , currY = head;
while (currY != null && currY.data != y) {
prevY = currY;
currY = currY.next;
}
if (currX == null || currY == null )
return ;
if (prevX != null )
prevX.next = currY;
else
head = currY;
if (prevY != null )
prevY.next = currX;
else
head = currX;
var temp = currX.next;
currX.next = currY.next;
currY.next = temp;
}
function push(new_data) {
var new_Node = new Node(new_data);
new_Node.next = head;
head = new_Node;
}
function printList() {
var tNode = head;
while (tNode != null ) {
document.write(tNode.data + " " );
tNode = tNode.next;
}
}
push(7);
push(6);
push(5);
push(4);
push(3);
push(2);
push(1);
document.write(
" Linked list before calling swapNodes()<br/> " )
;
printList();
swapNodes(4, 3);
document.write(
"<br/> Linked list after calling swapNodes() <br/>"
);
printList();
</script>
|
OutputLinked list before calling swapNodes() 1 2 3 4 5 6 7
Linked list after calling swapNodes() 1 2 4 3 5 6 7
Time Complexity: O(N)
Auxiliary Space: O(1)
Efficient Approach:
The above code can be optimized to search x and y in a single traversal. Two loops are used to keep the program simple.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
class Node {
public :
int data;
class Node* next;
Node( int val, Node* next)
: data(val)
, next(next)
{
}
void printList()
{
Node* node = this ;
while (node != NULL) {
cout << node->data << " " ;
node = node->next;
}
cout << endl;
}
};
void push(Node** head_ref, int new_data)
{
(*head_ref) = new Node(new_data, *head_ref);
}
void swap(Node*& a, Node*& b)
{
Node* temp = a;
a = b;
b = temp;
}
void swapNodes(Node** head_ref, int x, int y)
{
if (x == y)
return ;
Node **a = NULL, **b = NULL;
while (*head_ref) {
if ((*head_ref)->data == x)
a = head_ref;
else if ((*head_ref)->data == y)
b = head_ref;
head_ref = &((*head_ref)->next);
}
if (a && b) {
swap(*a, *b);
swap(((*a)->next), ((*b)->next));
}
}
int main()
{
Node* start = NULL;
push(&start, 7);
push(&start, 6);
push(&start, 5);
push(&start, 4);
push(&start, 3);
push(&start, 2);
push(&start, 1);
cout << "Linked list before calling swapNodes() " ;
start->printList();
swapNodes(&start, 6, 1);
cout << "Linked list after calling swapNodes() " ;
start->printList();
}
|
C
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
void push( struct Node** head_ref, int new_data)
{
Node* new_node = (Node*) malloc ( sizeof ( struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList(Node* node)
{
while (node != NULL) {
printf ( "%d " , node->data);
node = node->next;
}
}
void swap(Node* a, Node* b)
{
Node temp = *a;
*a = *b;
*b = temp;
}
void swapNodes(Node** head_ref, int x, int y)
{
if (x == y)
return ;
Node **a = NULL, **b = NULL;
while (*head_ref) {
if ((*head_ref)->data == x)
a = head_ref;
else if ((*head_ref)->data == y)
b = head_ref;
head_ref = &((*head_ref)->next);
}
if (a && b) {
swap(*a, *b);
swap(((*a)->next), ((*b)->next));
}
}
int main()
{
struct Node* start = NULL;
push(&start, 7);
push(&start, 6);
push(&start, 5);
push(&start, 4);
push(&start, 3);
push(&start, 2);
push(&start, 1);
printf ( "Linked list before calling swapNodes() " );
printList(start);
printf ( "\n" );
swapNodes(&start, 6, 1);
printf ( "Linked list after calling swapNodes() " );
printList(start);
}
|
Java
public class Solution {
class Node {
int data;
Node next;
public Node( int data)
{
this .data = data;
this .next = null ;
}
}
public Node head = null ;
public Node tail = null ;
public void addNode( int data)
{
Node newNode = new Node(data);
if (head == null ) {
head = newNode;
tail = newNode;
}
else {
tail.next = newNode;
tail = newNode;
}
}
public void swap( int n1, int n2)
{
Node prevNode1 = null , prevNode2 = null ,
node1 = head, node2 = head;
if (head == null ) {
return ;
}
if (n1 == n2)
return ;
while (node1 != null && node1.data != n1) {
prevNode1 = node1;
node1 = node1.next;
}
while (node2 != null && node2.data != n2) {
prevNode2 = node2;
node2 = node2.next;
}
if (node1 != null && node2 != null ) {
if (prevNode1 != null )
prevNode1.next = node2;
else
head = node2;
if (prevNode2 != null )
prevNode2.next = node1;
else
head = node1;
Node temp = node1.next;
node1.next = node2.next;
node2.next = temp;
}
else {
System.out.println( "Swapping is not possible" );
}
}
public void display()
{
Node current = head;
if (head == null ) {
System.out.println( "List is empty" );
return ;
}
while (current != null ) {
System.out.print(current.data + " " );
current = current.next;
}
System.out.println();
}
public static void main(String[] args)
{
Solution sList = new Solution();
sList.addNode( 1 );
sList.addNode( 2 );
sList.addNode( 3 );
sList.addNode( 4 );
sList.addNode( 5 );
sList.addNode( 6 );
sList.addNode( 7 );
System.out.println( "Original list: " );
sList.display();
sList.swap( 6 , 1 );
System.out.println( "List after swapping nodes: " );
sList.display();
}
}
|
Python3
class Node:
def __init__( self , val = None , next1 = None ):
self .data = val
self . next = next1
def printList( self ):
node = self
while (node ! = None ):
print (node.data, end = " " )
node = node. next
print ( " " )
def push(head_ref, new_data):
(head_ref) = Node(new_data, head_ref)
return head_ref
def swapNodes(head_ref, x, y):
head = head_ref
if (x = = y):
return None
a = None
b = None
while (head_ref. next ! = None ):
if ((head_ref. next ).data = = x):
a = head_ref
elif ((head_ref. next ).data = = y):
b = head_ref
head_ref = ((head_ref). next )
if (a ! = None and b ! = None ):
temp = a. next
a. next = b. next
b. next = temp
temp = a. next . next
a. next . next = b. next . next
b. next . next = temp
return head
start = None
start = push(start, 7 )
start = push(start, 6 )
start = push(start, 5 )
start = push(start, 4 )
start = push(start, 3 )
start = push(start, 2 )
start = push(start, 1 )
print ( "Linked list before calling swapNodes() " )
start.printList()
start = swapNodes(start, 6 , 1 )
print ( "Linked list after calling swapNodes() " )
start.printList()
|
C#
using System;
class GFG {
public class Node {
public int data;
public Node next;
public Node( int val, Node next1)
{
data = val;
next = next1;
}
public void printList()
{
Node node = this ;
while (node != null ) {
Console.Write(node.data + " " );
node = node.next;
}
Console.WriteLine();
}
}
static Node push(Node head_ref, int new_data)
{
(head_ref) = new Node(new_data, head_ref);
return head_ref;
}
static Node swapNodes(Node head_ref, int x, int y)
{
Node head = head_ref;
if (x == y)
return null ;
Node a = null , b = null ;
while (head_ref.next != null ) {
if ((head_ref.next).data == x) {
a = head_ref;
}
else if ((head_ref.next).data == y) {
b = head_ref;
}
head_ref = ((head_ref).next);
}
if (a != null && b != null ) {
Node temp = a.next;
a.next = b.next;
b.next = temp;
temp = a.next.next;
a.next.next = b.next.next;
b.next.next = temp;
}
return head;
}
public static void Main()
{
Node start = null ;
start = push(start, 7);
start = push(start, 6);
start = push(start, 5);
start = push(start, 4);
start = push(start, 3);
start = push(start, 2);
start = push(start, 1);
Console.Write(
"Linked list before calling swapNodes() " );
start.printList();
start = swapNodes(start, 6, 1);
Console.Write(
"Linked list after calling swapNodes() " );
start.printList();
}
}
|
Javascript
<script>
class Node {
constructor(val) {
this .data = val;
this .next = null ;
}
}
var head = null ;
var tail = null ;
function addNode(data) {
var newNode = new Node(data);
if (head == null ) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
tail = newNode;
}
}
function swap(n1 , n2) {
var prevNode1 = null , prevNode2 = null , node1 = head, node2 = head;
if (head == null ) {
return ;
}
if (n1 == n2)
return ;
while (node1 != null && node1.data != n1) {
prevNode1 = node1;
node1 = node1.next;
}
while (node2 != null && node2.data != n2) {
prevNode2 = node2;
node2 = node2.next;
}
if (node1 != null && node2 != null ) {
if (prevNode1 != null )
prevNode1.next = node2;
else
head = node2;
if (prevNode2 != null )
prevNode2.next = node1;
else
head = node1;
var temp = node1.next;
node1.next = node2.next;
node2.next = temp;
} else {
document.write( "Swapping is not possible" );
}
}
function display() {
var current = head;
if (head == null ) {
document.write( "List is empty" );
return ;
}
while (current != null ) {
document.write(current.data + " " );
current = current.next;
}
document.write();
}
addNode(1);
addNode(2);
addNode(3);
addNode(4);
addNode(5);
addNode(6);
addNode(7);
document.write( "Original list:<br/> " );
display();
swap(6, 1);
document.write( "<br/>List after swapping nodes: <br/>" );
display();
</script>
|
OutputLinked list before calling swapNodes() 1 2 3 4 5 6 7
Linked list after calling swapNodes() 6 2 3 4 5 1 7
Time complexity: O(N)
Auxiliary Space: O(1)