Swap nodes in a linked list without swapping data
Last Updated :
20 Sep, 2024
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>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int x) {
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, int x, int y) {
// Nothing to do if x and y are the same
if (x == y) return head;
Node *prevX = nullptr, *currX = nullptr;
Node *prevY = nullptr, *currY = nullptr;
Node *curr = head;
// First loop to find x
while (curr != nullptr) {
if (curr->data == x) {
currX = curr;
break;
}
prevX = curr;
curr = curr->next;
}
curr = head;
// Second loop to find y
while (curr != nullptr) {
if (curr->data == y) {
currY = curr;
break;
}
prevY = curr;
curr = curr->next;
}
// If either x or y is not present, nothing to do
if (currX == nullptr || currY == nullptr) return head;
// If x is not head of the linked list
if (prevX != nullptr) {
prevX->next = currY;
} else {
head = currY;
}
// If y is not head of the linked list
if (prevY != nullptr) {
prevY->next = currX;
} else {
head = currX;
}
// Swap next pointers
Node* temp = currY->next;
currY->next = currX->next;
currX->next = temp;
return head;
}
void print(Node* curr) {
while (curr != nullptr) {
cout << curr->data << " ";
curr = curr->next;
}
cout << endl;
}
int main() {
// Constructed linked list:
// 1->2->3->4->5
Node* head = new Node(1);
head->next = new Node(2);
head->next->next = new Node(3);
head->next->next->next = new Node(4);
head->next->next->next->next = new Node(5);
head = swapNodes(head, 4, 3);
print(head);
return 0;
}
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>
struct Node {
int data;
struct Node* next;
};
// Function to swap nodes x and y in linked list by
// changing links and return the updated head
struct Node* swapNodes(struct Node* head, int x, int y) {
// Nothing to do if x and y are the same
if (x == y)
return head;
struct Node *prevX = NULL, *currX = NULL;
struct Node *prevY = NULL, *currY = NULL;
struct Node *curr = head;
// First loop to find x
while (curr != NULL) {
if (curr->data == x) {
currX = curr;
break;
}
prevX = curr;
curr = curr->next;
}
curr = head;
// Second loop to find y
while (curr != NULL) {
if (curr->data == y) {
currY = curr;
break;
}
prevY = curr;
curr = curr->next;
}
// If either x or y is not present, nothing to do
if (currX == NULL || currY == NULL)
return head;
// If x is not head of the linked list
if (prevX != NULL)
prevX->next = currY;
else
head = currY;
// If y is not head of the linked list
if (prevY != NULL)
prevY->next = currX;
else
head = currX;
// Swap next pointers
struct Node* temp = currY->next;
currY->next = currX->next;
currX->next = temp;
return head;
}
void print(struct Node* curr) {
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
printf("\n");
}
struct Node* createNode(int x) {
struct Node* node =
(struct Node*)malloc(sizeof(struct Node));
node->data = x;
node->next = NULL;
return node;
}
int main() {
// Constructed linked list: 1->2->3->4->5
struct Node* 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);
return 0;
}
Java
// Java program to swap the nodes of a linked list rather
// than swapping the data from the nodes.
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
class GfG {
// Function to swap nodes x and y in linked list by changing links
static Node swapNodes(Node head, int x, int y) {
// Nothing to do if x and y are the same
if (x == y) {
return head;
}
Node prevX = null, currX = null;
Node prevY = null, currY = null;
Node curr = head;
// First loop to find x
while (curr != null) {
if (curr.data == x) {
currX = curr;
break;
}
prevX = curr;
curr = curr.next;
}
curr = head;
// Second loop to find y
while (curr != null) {
if (curr.data == y) {
currY = curr;
break;
}
prevY = curr;
curr = curr.next;
}
// If either x or y is not present, nothing to do
if (currX == null || currY == null) {
return head;
}
// If x is not head of the linked list
if (prevX != null) {
prevX.next = currY;
} else {
head = currY;
}
// If y is not head of the linked list
if (prevY != null) {
prevY.next = currX;
} else {
head = currX;
}
// Swap next pointers
Node temp = currY.next;
currY.next = currX.next;
currX.next = temp;
return head;
}
static void printList(Node curr) {
while (curr != null) {
System.out.print(curr.data + " ");
curr = curr.next;
}
System.out.println();
}
public static void main(String[] args) {
// Constructed linked list: 1->2->3->4->5
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(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.
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Function to swap nodes x and y in linked
# list by changing links
def swapNodes(head, x, y):
# Nothing to do if x and y are the same
if x == y:
return head
prevX = None
currX = head
while currX and currX.data != x:
prevX = currX
currX = currX.next
prevY = None
currY = head
while currY and currY.data != y:
prevY = currY
currY = currY.next
# If either x or y is not present, nothing to do
if currX is None or currY is None:
return head
# If x is not head of the linked list
if prevX:
prevX.next = currY
else:
head = currY
# If y is not head of the linked list
if prevY:
prevY.next = currX
else:
head = currX
# Swap next pointers
currX.next, currY.next = currY.next, currX.next
return head
def printList(curr):
while curr:
print(curr.data, end=" ")
curr = curr.next
print()
if __name__ == "__main__":
# Constructed linked list: 1->2->3->4->5
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 = 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.
using System;
class Node {
public int data;
public Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
class GfG {
// Function to swap nodes x and y in linked list by changing links
static Node swapNodes(Node head, int x, int y) {
// Nothing to do if x and y are the same
if (x == y)
return head;
Node prevX = null;
Node currX = head;
// Find currX and prevX
while (currX != null && currX.data != x) {
prevX = currX;
currX = currX.next;
}
Node prevY = null;
Node currY = head;
// Find currY and prevY
while (currY != null && currY.data != y) {
prevY = currY;
currY = currY.next;
}
// If either x or y is not present, nothing to do
if (currX == null || currY == null)
return head;
// If x is not head of the linked list
if (prevX != null)
prevX.next = currY;
else
head = currY;
// If y is not head of the linked list
if (prevY != null)
prevY.next = currX;
else
head = currX;
// Swap next pointers
Node temp = currY.next;
currY.next = currX.next;
currX.next = temp;
return head;
}
static void printList(Node curr) {
while (curr != null) {
Console.Write(curr.data + " ");
curr = curr.next;
}
Console.WriteLine();
}
static void Main(string[] args) {
// Constructed linked list: 1->2->3->4->5
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(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.
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
// Function to swap nodes x and y in linked
// list by changing links
function swapNodes(head, x, y) {
// Nothing to do if x and y are the same
if (x === y) return head;
let prevX = null, currX = head;
// Find currX and prevX
while (currX && currX.data !== x) {
prevX = currX;
currX = currX.next;
}
let prevY = null, currY = head;
// Find currY and prevY
while (currY && currY.data !== y) {
prevY = currY;
currY = currY.next;
}
// If either x or y is not present, nothing to do
if (!currX || !currY) return head;
// If x is not head of the linked list
if (prevX) prevX.next = currY;
else head = currY;
// If y is not head of the linked list
if (prevY) prevY.next = currX;
else head = currX;
// Swap next pointers
let temp = currY.next;
currY.next = currX.next;
currX.next = temp;
return head;
}
function printList(curr) {
while (curr) {
console.log(curr.data + " ");
curr = curr.next;
}
console.log();
}
// Constructed linked list:
// 1->2->3->4->5
let head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);
head = swapNodes(head, 4, 3);
printList(head);
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 search x and y in 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>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int x) {
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, int x, int y) {
// Nothing to do if x and y are same
if (x == y)
return head;
Node *prevX = nullptr, *currX = nullptr;
Node *prevY = nullptr, *currY = nullptr;
Node *prev = nullptr, *curr = head;
// Single loop to find both x and y
while (curr != nullptr) {
if (curr->data == x) {
prevX = prev;
currX = curr;
} else if (curr->data == y) {
prevY = prev;
currY = curr;
}
prev = curr;
curr = curr->next;
}
// If either x or y is not present, nothing to do
if (currX == nullptr || currY == nullptr)
return head;
// If x is not head of the linked list
if (prevX != nullptr)
prevX->next = currY;
else // Else make y the new head
head = currY;
// If y is not head of the linked list
if (prevY != nullptr)
prevY->next = currX;
else
// Else make x the new head
head = currX;
// Swap next pointers
Node* temp = currY->next;
currY->next = currX->next;
currX->next = temp;
return head;
}
void print(Node* curr) {
while (curr != nullptr) {
cout << curr->data << " ";
curr = curr->next;
}
}
int main() {
// Constructed linked list:
// 1->2->3->4->5
Node* head = new Node(1);
head->next = new Node(2);
head->next->next = new Node(3);
head->next->next->next = new Node(4);
head->next->next->next->next = new Node(5);
head = swapNodes(head, 4, 3);
print(head);
return 0;
}
C
// C program to swaps the nodes of linked list rather
// than swapping the data from the nodes.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
// Function to swap nodes x and y in linked list by
// changing links and return the updated head
struct Node* swapNodes(struct Node* head, int x, int y) {
// Nothing to do if x and y are same
if (x == y)
return head;
struct Node *prevX = NULL, *currX = NULL;
struct Node *prevY = NULL, *currY = NULL;
struct Node *prev = NULL, *curr = head;
// Single loop to find both x and y
while (curr != NULL) {
if (curr->data == x) {
prevX = prev;
currX = curr;
} else if (curr->data == y) {
prevY = prev;
currY = curr;
}
prev = curr;
curr = curr->next;
}
// If either x or y is not present, nothing to do
if (currX == NULL || currY == NULL)
return head;
// If x is not head of the linked list
if (prevX != NULL)
prevX->next = currY;
else
head = currY;
// If y is not head of the linked list
if (prevY != NULL)
prevY->next = currX;
else
head = currX;
// Swap next pointers
struct Node* temp = currY->next;
currY->next = currX->next;
currX->next = temp;
return head;
}
void print(struct Node* curr) {
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
}
struct Node* createNode(int x) {
struct Node* node =
(struct Node*)malloc(sizeof(struct Node));
node->data = x;
node->next = NULL;
return node;
}
int main() {
// Constructed linked list:
// 1->2->3->4->5
struct Node* 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);
return 0;
}
Java
// Java program to swaps the nodes of linked list rather
// than swapping the data from the nodes.
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
class GfG {
// Function to swap nodes x and y in linked list by
// changing links and return the updated head
static Node swapNodes(Node head, int x, int y) {
// Nothing to do if x and y are same
if (x == y)
return head;
Node prevX = null, currX = null;
Node prevY = null, currY = null;
Node prev = null, curr = head;
// Single loop to find both x and y
while (curr != null) {
if (curr.data == x) {
prevX = prev;
currX = curr;
} else if (curr.data == y) {
prevY = prev;
currY = curr;
}
prev = curr;
curr = curr.next;
}
// If either x or y is not present, nothing to do
if (currX == null || currY == null)
return head;
// If x is not head of the linked list
if (prevX != null)
prevX.next = currY;
else
// Else make y the new head
head = currY;
// If y is not head of the linked list
if (prevY != null)
prevY.next = currX;
else
// Else make x the new head
head = currX;
// Swap next pointers
Node temp = currY.next;
currY.next = currX.next;
currX.next = temp;
return head;
}
static void printList(Node curr) {
while (curr != null) {
System.out.print(curr.data + " ");
curr = curr.next;
}
}
public static void main(String[] args) {
// Constructed linked list:
// 1->2->3->4->5
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(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.
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Function to swap nodes x and y in linked list by
# changing links and return the updated head
def swapNodes(head, x, y):
# Nothing to do if x and y are same
if x == y:
return head
prevX = None
currX = None
prevY = None
currY = None
prev = None
curr = head
# Single loop to find both x and y
while curr:
if curr.data == x:
prevX = prev
currX = curr
elif curr.data == y:
prevY = prev
currY = curr
prev = curr
curr = curr.next
# If either x or y is not present, nothing to do
if currX is None or currY is None:
return head
# If x is not head of the linked list
if prevX is not None:
prevX.next = currY
else:
head = currY
# If y is not head of the linked list
if prevY is not None:
prevY.next = currX
else:
# Else make x the new head
head = currX
# Swap next pointers
temp = currY.next
currY.next = currX.next
currX.next = temp
return head
def printList(curr):
while curr:
print(curr.data, end=" ")
curr = curr.next
if __name__ == "__main__":
# Constructed linked list:
# 1->2->3->4->5
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 = swapNodes(head, 4, 3)
printList(head)
C#
// C# program to swaps the nodes of linked list rather
// than swapping the data from the nodes.
using System;
class Node {
public int data;
public Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
class GfG {
// Function to swap nodes x and y in linked list by
// changing links and return the updated head
static Node swapNodes(Node head, int x, int y) {
// Nothing to do if x and y are same
if (x == y)
return head;
Node prevX = null, currX = null;
Node prevY = null, currY = null;
Node prev = null, curr = head;
// Single loop to find both x and y
while (curr != null) {
if (curr.data == x) {
prevX = prev;
currX = curr;
} else if (curr.data == y) {
prevY = prev;
currY = curr;
}
prev = curr;
curr = curr.next;
}
// If either x or y is not present, nothing to do
if (currX == null || currY == null)
return head;
// If x is not head of the linked list
if (prevX != null)
prevX.next = currY;
else
// Else make y the new head
head = currY;
// If y is not head of the linked list
if (prevY != null)
prevY.next = currX;
else
// Else make x the new head
head = currX;
// Swap next pointers
Node temp = currY.next;
currY.next = currX.next;
currX.next = temp;
return head;
}
static void printList(Node curr) {
while (curr != null) {
Console.Write(curr.data + " ");
curr = curr.next;
}
}
static void Main(string[] args) {
// Constructed linked list:
// 1->2->3->4->5
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(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.
class Node {
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
function swapNodes(head, x, y) {
// Nothing to do if x and y are same
if (x === y) return head;
let prevX = null, currX = null;
let prevY = null, currY = null;
let prev = null, curr = head;
// Single loop to find both x and y
while (curr) {
if (curr.data === x) {
prevX = prev;
currX = curr;
} else if (curr.data === y) {
prevY = prev;
currY = curr;
}
prev = curr;
curr = curr.next;
}
// If either x or y is not present, nothing to do
if (!currX || !currY) return head;
// If x is not head of the linked list
if (prevX) prevX.next = currY;
else head = currY;
// If y is not head of the linked list
if (prevY) prevY.next = currX;
else head = currX;
// Swap next pointers
let temp = currY.next;
currY.next = currX.next;
currX.next = temp;
return head;
}
function printList(curr) {
while (curr) {
console.log(curr.data + " ");
curr = curr.next;
}
}
// Constructed linked list:
// 1->2->3->4->5
let head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);
head = swapNodes(head, 4, 3);
printList(head);
Time Complexity: O(n), where n is the number of nodes in linked list.
Auxiliary Space: O(1)
Similar Reads
Reverse a Doubly Linked List without swapping nodes
Write a program to reverse the given Doubly Linked List. See below diagrams for example. (a) Original Doubly Linked List (b) Reversed Doubly Linked List Approach: In the previous post, doubly linked list is being reversed by swapping prev and next pointers for all nodes, changing prev of the head (o
10 min read
Javascript Program For Swapping Nodes In A Linked List Without Swapping Data
Given a linked list and two keys in it, swap nodes for two given keys. Nodes should be swapped by changing links. Swapping data of nodes may be expensive in many situations when data contains many fields. It may be assumed that all keys in the linked list are distinct. Examples: Input : 10->15-
6 min read
Swap given nodes in a Doubly Linked List without modifying data
Given a doubly linked list having all unique elements and two keys X and Y, the task is to swap nodes for two given keys by changing links only. Note: It may be considered that X and Y are always present in the list. Examples: Input: list = 1 <-> 8 <-> 7 <-> 9 <-> 4, X = 1, Y
11 min read
Replace nodes with duplicates in linked list
Given a linked list that contains some random integers from 1 to n with many duplicates. Replace each duplicate element that is present in the linked list with the values n+1, n+2, n+3 and so on(starting from left to right in the given linked list). Examples: Input : 1 3 1 4 4 2 1 Output : 1 3 5 4 6
9 min read
Reverse alternate K nodes in a Singly Linked List
Given a linked list, The task is to reverse alternate k nodes. If the number of nodes left at the end of the list is fewer than k, reverse these remaining nodes or leave them in their original order, depending on the alternation pattern. Example: Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -
15+ min read
Reverse a Doubly Linked List by swapping data
Given a Doubly Linked List, we are asked to reverse the list in place without using any extra space. Examples: Input : 1 <--> 2 <--> 5 <--> 6 <--> 7 Output : 7 <--> 6 <--> 5 <--> 2 <--> 1 Input : 11 <--> 22 <--> 33 <--> 22 <-->
10 min read
Print reverse of a Linked List without actually reversing
Given a singly linked list. The task is to print the linked list in reverse order without actually reversing the linked list. Examples: Input: head : 1 -> 2 -> 3 -> 4 -> NULL Output: 4 -> 3 -> 2 -> 1 -> NULL Input: head: 1 -> 2 -> 3 -> 4 -> 5 -> NULL Output: 5
8 min read
Print nodes of linked list at given indexes
Given head of two singly linked lists, first one is sorted and the other one is unsorted. The task is to print the elements of the second linked list according to the position pointed out by the data in the first linked list. For example, if the first linked list is 1->2->5, then you have to p
15+ min read
Alternating split of a given Singly Linked List | Set 1
Write a function AlternatingSplit() that takes one list and divides up its nodes to make two smaller lists 'a' and 'b'. The sublists should be made from alternating elements in the original list. So if the original list is 0->1->0->1->0->1 then one sublist should be 0->0->0 and
15+ min read
Reverse nodes of a linked list without affecting the special characters
Given a linked list of alphabets and special characters. Reverse the given linked list without affecting the position of the special characters. Examples: Input: g -> @ -> e -> # -> e -> $ -> k -> s -> NULL Output: s -> @ -> k -> # -> e -> $ -> e -> g -
12 min read