Open In App

Javascript Program For Swapping Nodes In A Linked List Without Swapping Data

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
1 Like
Like
Report

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->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

This may look a simple problem, but is an interesting question as it has the following cases to be handled. 

  1. x and y may or may not be adjacent.
  2. Either x or y may be a head node.
  3. Either x or y may be the last node.
  4. x and/or y may not be present in the linked list.

How to write a clean working code that handles all the above possibilities.

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 implementation of the above approach. 


Output
Linked list before calling swapNodes()
1
2
3
4
5
6
7
Linked list after calling swapNodes()
1
2
4
3
5
6
7

Complexity Analysis:

  • Time Complexity: O(n)
  • Auxiliary Space: O(1)

Optimizations: The above code can be optimized to search x and y in single traversal. Two loops are used to keep program simple.

Simpler approach:


Output
Original list:
1
2
3
4
5
6
7
List after swapping nodes:
6
2
3
4
5
1
7

Complexity Analysis:

  • Time Complexity: O(n)
  • Auxiliary Space: O(1)

Please refer complete article on Swap nodes in a linked list without swapping data for more details!


Article Tags :

Similar Reads