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)