C++ 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.
C++
// C++ program to swap the nodes of linked list rather
// than swapping the field from the nodes.
#include <bits/stdc++.h>
using namespace std;
// A linked list node
class Node
{
public:
int data;
Node* next;
};
// Function to swap nodes x and y in
// linked list by changing links
void swapNodes(Node** head_ref,
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_ref;
while (currX && currX->data != x)
{
prevX = currX;
currX = currX->next;
}
// Search for y (keep track of
// prevY and CurrY
Node *prevY = NULL,
*currY = *head_ref;
while (currY && 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
// Else make y as new head
*head_ref = currY;
// If y is not head of linked list
if (prevY != NULL)
prevY->next = currX;
else // Else make x as new head
*head_ref = currX;
// Swap next pointers
Node* temp = currY->next;
currY->next = currX->next;
currX->next = temp;
}
// Function to add a node at the
// beginning of List
void push(Node** head_ref,
int new_data)
{
// Allocate node
Node* new_node = new Node();
// Put in the data
new_node->data = new_data;
// Link the old list off the new node
new_node->next = (*head_ref);
// Move the head to point to the
// new node
(*head_ref) = new_node;
}
// Function to print nodes in a
// given linked list
void printList(Node* node)
{
while (node != NULL)
{
cout << node->data << " ";
node = node->next;
}
}
// Driver code
int main()
{
Node* start = NULL;
/* The constructed linked list is:
1->2->3->4->5->6->7 */
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 << "Linked list after calling swapNodes() ";
printList(start);
return 0;
}
// This is code is contributed by rathbhupendra
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:
C++
// C++ program to swap two given nodes
// of a linked list
#include <iostream>
using namespace std;
// A linked list node class
class Node
{
public:
int data;
class Node* next;
// constructor
Node(int val, Node* next)
: data(val)
, next(next)
{
}
// print list from this
// to last till null
void printList()
{
Node* node = this;
while (node != NULL)
{
cout << node->data << " ";
node = node->next;
}
cout << endl;
}
};
// Function to add a node
// at the beginning of List
void push(Node** head_ref,
int new_data)
{
// Allocate node
(*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)
{
// Nothing to do if x and
// y are same
if (x == y)
return;
Node **a = NULL, **b = NULL;
// Search for x and y in the linked list
// and store their pointer in a and b
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 we have found both a and b
// in the linked list swap current
// pointer and next pointer of these
if (a && b)
{
swap(*a, *b);
swap(((*a)->next), ((*b)->next));
}
}
// Driver code
int main()
{
Node* start = NULL;
// The constructed linked list is:
// 1->2->3->4->5->6->7
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();
}
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
C++ 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 the same. Examples: Input: 17->15->8->12->10->5->4->1->7->6-
7 min read
C++ 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
C++ Program for Deleting a Node in a Linked List
Write a C++ program to delete a node from the given link list.ExamplesInput: Linked List: 10 -> 20 -> 30 -> 40 -> 50, Position to delete: 3Output: 10 -> 20 -> 40 -> 50Explanation: The node at position 3 is removed. The list then connects node 20 directly to node 40.Input: Linked
6 min read
C++ 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
5 min read
C++ Program For 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
5 min read
C++ 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
C++ 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 -
7 min read
C++ Program For Deleting A Node In A Doubly Linked List
Pre-requisite: Doubly Link List Set 1| Introduction and Insertion Write a function to delete a given node in a doubly-linked list. Original Doubly Linked List Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Approach: The deletion of a node in a doubly-linked list
4 min read
C++ Program For Writing A Function To Delete A Linked List
Algorithm For C++:Iterate through the linked list and delete all the nodes one by one. The main point here is not to access the next of the current pointer if the current pointer is deleted. Implementation: C++ // C++ program to delete a linked list #include <bits/stdc++.h> using namespace std
2 min read
C++ Program For Removing Duplicates From A Sorted Linked List
Write a function that takes a list sorted in non-decreasing order and deletes any duplicate nodes from the list. The list should only be traversed once. For example if the linked list is 11->11->11->21->43->43->60 then removeDuplicates() should convert the list to 11->21->43-
9 min read