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
Menu driven program for all operations on singly linked list in C A Linked List is a linear data structure that consists of two parts: one is the data part and the other is the address part. In this article, all the common operations of a singly linked list are discussed in one menu-driven program.Operations to be PerformedcreateList(): To create the list with the
8 min read
Rearrange a Linked List in Zig-Zag fashion | Set-2 Given a linked list, rearrange it such that converted list should be of the form a < b > c < d > e < f .. where a, b, c.. are consecutive data node of linked list. Note that it is not allowed to swap data. Examples: Input: 1->2->3->4 Output: 1->3->2->4 Input: 11->
13 min read
Javascript Program For Pairwise Swapping Elements Of A Given Linked List By Changing Links Given a singly linked list, write a function to swap elements pairwise. For example, if the linked list is 1->2->3->4->5->6->7 then the function should change it to 2->1->4->3->6->5->7, and if the linked list is 1->2->3->4->5->6 then the function sh
4 min read
Pairwise Swap Nodes of a given linked list by changing links Given a singly linked list, write a function to swap elements pairwise. For example, if the linked list is 1->2->3->4->5->6->7 then the function should change it to 2->1->4->3->6->5->7, and if the linked list is 1->2->3->4->5->6 then the function sh
15+ min read
XOR Linked List - Pairwise swap elements of a given linked list Given a XOR linked list, the task is to pairwise swap the elements of the given XOR linked list . Examples: Input: 4 <-> 7 <-> 9 <-> 7Output: 7 <-> 4 <-> 7 <-> 9Explanation:First pair of nodes are swapped to formed the sequence {4, 7} and second pair of nodes are
12 min read
C 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-
4 min read