Java Program For Swapping Nodes In A Linked List Without Swapping Data
Last Updated :
30 Mar, 2022
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.
- x and y may or may not be adjacent.
- Either x or y may be a head node.
- Either x or y may be the last node.
- 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.
Java
// Java program to swap two given nodes
// of a linked list
class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
class LinkedList
{
// head of list
Node head;
/* Function to swap Nodes x and y in
linked list by changing links */
public void swapNodes(int x, int y)
{
// Nothing to do if x and y
// are same
if (x == y)
return;
// Search for x (keep track of
// prevX and CurrX)
Node prevX = null, currX = head;
while (currX != null &&
currX.data != x)
{
prevX = currX;
currX = currX.next;
}
// Search for y (keep track of
// prevY and currY)
Node prevY = null, currY = head;
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;
// If x is not head of linked list
if (prevX != null)
prevX.next = currY;
else // make y the new head
head = currY;
// If y is not head of linked list
if (prevY != null)
prevY.next = currX;
else // make x the new head
head = currX;
// Swap next pointers
Node temp = currX.next;
currX.next = currY.next;
currY.next = temp;
}
// Function to add Node at
// beginning of list.
public void push(int new_data)
{
// 1. alloc the Node and put the data
Node new_Node = new Node(new_data);
// 2. Make next of new Node as head
new_Node.next = head;
// 3. Move the head to point to new Node
head = new_Node;
}
/* This function prints contents of
linked list starting from the given Node */
public void printList()
{
Node tNode = head;
while (tNode != null)
{
System.out.print(tNode.data + " ");
tNode = tNode.next;
}
}
// Driver code
public static void main(String[] args)
{
LinkedList llist = new LinkedList();
/* The constructed linked list is:
1->2->3->4->5->6->7 */
llist.push(7);
llist.push(6);
llist.push(5);
llist.push(4);
llist.push(3);
llist.push(2);
llist.push(1);
System.out.print(
"Linked list before calling swapNodes() ");
llist.printList();
llist.swapNodes(4, 3);
System.out.print(
"Linked list after calling swapNodes() ");
llist.printList();
}
}
// This code is contributed by Rajat Mishra
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
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:
Java
// Java program to swap two given nodes
// of a linked list
public class Solution
{
// Represent a node of the
// singly linked list
class Node
{
int data;
Node next;
public Node(int data)
{
this.data = data;
this.next = null;
}
}
// Represent the head and tail
// of the singly linked list
public Node head = null;
public Node tail = null;
// addNode() will add a new node
// to the list
public void addNode(int data)
{
// Create a new node
Node newNode = new Node(data);
// Checks if the list is empty
if (head == null)
{
// If list is empty, both head and
// tail will point to new node
head = newNode;
tail = newNode;
}
else
{
// newNode will be added after tail
// such that tail's next will point
// to newNode
tail.next = newNode;
// newNode will become new tail of
// the list
tail = newNode;
}
}
// swap() will swap the given two nodes
public void swap(int n1, int n2)
{
Node prevNode1 = null, prevNode2 = null,
node1 = head, node2 = head;
// Checks if list is empty
if (head == null)
{
return;
}
// If n1 and n2 are equal, then
// list will remain the same
if (n1 == n2)
return;
// Search for node1
while (node1 != null &&
node1.data != n1)
{
prevNode1 = node1;
node1 = node1.next;
}
// Search for node2
while (node2 != null &&
node2.data != n2)
{
prevNode2 = node2;
node2 = node2.next;
}
if (node1 != null &&
node2 != null)
{
// If previous node to node1 is not
// null then, it will point to node2
if (prevNode1 != null)
prevNode1.next = node2;
else
head = node2;
// If previous node to node2 is not
// null then, it will point to node1
if (prevNode2 != null)
prevNode2.next = node1;
else
head = node1;
// Swaps the next nodes of node1
// and node2
Node temp = node1.next;
node1.next = node2.next;
node2.next = temp;
}
else
{
System.out.println("Swapping is not possible");
}
}
// display() will display all the
// nodes present in the list
public void display()
{
// Node current will point to head
Node current = head;
if (head == null)
{
System.out.println("List is empty");
return;
}
while (current != null)
{
// Prints each node by incrementing
// pointer
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
public static void main(String[] args)
{
Solution sList = new Solution();
// Add nodes to the list
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();
// Swaps the node 2 with node 5
sList.swap(6, 1);
System.out.println(
"List after swapping nodes: ");
sList.display();
}
}
Output:
Linked 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)
Please refer complete article on Swap nodes in a linked list without swapping data for more details!
Similar Reads
Java Program For Segregating Even And Odd Nodes In A Linked List
Given a Linked List of integers, write a function to modify the linked list such that all even numbers appear before all the odd numbers in the modified linked list. Also, keep the order of even and odd numbers same.Examples: Input: 17->15->8->12->10->5->4->1->7->6->NUL
6 min read
Java Program For Pairwise Swapping Elements Of A Given Linked List
Given a singly linked list, write a function to swap elements pairwise. Input: 1->2->3->4->5->6->NULL Output: 2->1->4->3->6->5->NULL Input: 1->2->3->4->5->NULL Output: 2->1->4->3->5->NULL Input: 1->NULL Output: 1->NULL For examp
3 min read
Java Program For Printing Reverse Of A Linked List Without Actually Reversing
Given a linked list, print reverse of it using a recursive function. For example, if the given linked list is 1->2->3->4, then output should be 4->3->2->1.Note that the question is only about printing the reverse. To reverse the list itself see this Difficulty Level: Rookie Algorit
2 min read
Java Program For Deleting A Node In A Linked List
We have discussed Linked List Introduction and Linked List Insertion in previous posts on a singly linked list.Let us formulate the problem statement to understand the deletion process. Given a 'key', delete the first occurrence of this key in the linked list. Iterative Method:To delete a node from
3 min read
Java Program For Swapping Kth Node From Beginning With Kth Node From End In A Linked List
Given a singly linked list, swap kth node from beginning with kth node from end. Swapping of data is not allowed, only pointers should be changed. This requirement may be logical in many situations where the linked list data part is huge (For example student details line Name, RollNo, Address, ..etc
5 min read
Java Program For Insertion Sort In A Singly Linked List
We have discussed Insertion Sort for arrays. In this article we are going to discuss Insertion Sort for linked list. Below is a simple insertion sort algorithm for a linked list. 1) Create an empty sorted (or result) list. 2) Traverse the given list, do following for every node. ......a) Insert curr
4 min read
Java Program For Inserting A Node In A Linked List
We have introduced Linked Lists in the previous post. We also created a simple linked list with 3 nodes and discussed linked list traversal.All programs discussed in this post consider the following representations of the linked list. Java // Linked List Class class LinkedList { // Head of list Node
7 min read
Java Program For Cloning A Linked List With Next And Random Pointer In O(1) Space
Given a linked list having two pointers in each node. The first one points to the next node of the list, however, the other pointer is random and can point to any node of the list. Write a program that clones the given list in O(1) space, i.e., without any extra space. Examples: Input : Head of the
4 min read
Java Program For Writing A Function To Get Nth Node In A Linked List
Write a GetNth() function that takes a linked list and an integer index and returns the data value stored in the node at that index position. Example: Input: 1->10->30->14, index = 2 Output: 30 The node at index 2 is 30Recommended: Please solve it on "PRACTICE" first, before moving on to th
4 min read
Java Program For Rearranging A Given Linked List In-Place.
Given a singly linked list L0 -> L1 -> ⦠-> Ln-1 -> Ln. Rearrange the nodes in the list so that the new formed list is : L0 -> Ln -> L1 -> Ln-1 -> L2 -> Ln-2 ...You are required to do this in place without altering the nodes' values. Examples: Input: 1 -> 2 -> 3 -
8 min read