Swap given nodes in a Doubly Linked List without modifying data

• Difficulty Level : Hard
• Last Updated : 05 Jul, 2022

Given a doubly linked list having all unique elements and two keys X and Y, the task is to swap nodes for two given keys by changing links only.

Note: It may be considered that X and Y are always present in the list.

Examples:

Input:  list = 1 <-> 8 <-> 7 <-> 9 <-> 4, X = 1, Y = 4
Output: 4 <-> 8 <-> 7 <-> 9 <-> 1

Input: list = 0 <-> 1, X = 0, Y = 1
Output: 1 <-> 0

Approach: The problem can be solved by traversing pointers to nodes having values X and Y and swap them.

Follow the steps mentioned below:

• Search X and Y in the given doubly linked list.
• After searching, swap the nodes by making the previous adjacent pointer of X to be previous adjacent pointer of Y and next adjacent pointer of X to be next adjacent pointer of Y and vice versa.

Below is the implementation of the above approach:

C++

 `// C++ code to implement the above approach`   `#include ` `using` `namespace` `std;`   `// Link list Node Class` `class` `Node {` `public``:` `    ``int` `data;` `    ``Node* prev;` `    ``Node* next;`   `    ``// Constructor function` `    ``Node(``int` `data)` `    ``{` `        ``this``->data = data;` `        ``this``->prev = NULL;` `        ``this``->next = NULL;` `    ``}` `};`   `// Function to print linked list` `void` `print(Node* head)` `{` `    ``Node* temp = head;`   `    ``// Iterate until node is NOT NULL` `    ``while` `(temp != NULL) {` `        ``cout << temp->data << ``" "``;` `        ``temp = temp->next;` `    ``}` `    ``cout << endl;` `}`   `// Function to push a node in DLL` `void` `push(Node*& head, Node*& tail,` `          ``int` `item)` `{`   `    ``// DLL is empty` `    ``if` `(tail == NULL) {`   `        ``Node* temp = ``new` `Node(item);` `        ``tail = temp;` `        ``head = temp;` `    ``}`   `    ``// DLL is not empty` `    ``else` `{` `        ``Node* temp = ``new` `Node(item);` `        ``tail->next = temp;` `        ``temp->prev = tail;` `        ``tail = temp;` `    ``}` `}`   `// Function to find the nodes` `// which have to be swapped` `pair find(Node*& head,` `                        ``int` `x, ``int` `y)` `{` `    ``Node* N1 = NULL;` `    ``Node* N2 = NULL;` `    ``Node* temp = head;`   `    ``// Traversing the list` `    ``while` `(temp != NULL) {` `        ``if` `(temp->data == x)` `            ``N1 = temp;` `        ``else` `if` `(temp->data == y)` `            ``N2 = temp;` `        ``temp = temp->next;` `    ``}` `    ``return` `make_pair(N1, N2);` `}`   `// Function to swap the nodes` `// consisting of x and y` `void` `swap(Node*& head, Node*& tail,` `          ``int` `x, ``int` `y)` `{`   `    ``// Edge Cases` `    ``if` `(head == NULL || head->next == NULL` `        ``|| x == y)` `        ``return``;`   `    ``// Finding the Nodes` `    ``pair p = find(head, x, y);`   `    ``Node* Node1 = p.first;` `    ``Node* Node2 = p.second;`   `    ``if` `(Node1 == head)` `        ``head = Node2;` `    ``else` `if` `(Node2 == head)` `        ``head = Node1;` `    ``if` `(Node1 == tail)` `        ``tail = Node2;` `    ``else` `if` `(Node2 == tail)` `        ``tail = Node1;`   `    ``// Swapping Node1 and Node2` `    ``Node* temp;` `    ``temp = Node1->next;` `    ``Node1->next = Node2->next;` `    ``Node2->next = temp;`   `    ``if` `(Node1->next != NULL)` `        ``Node1->next->prev = Node1;` `    ``if` `(Node2->next != NULL)` `        ``Node2->next->prev = Node2;`   `    ``temp = Node1->prev;` `    ``Node1->prev = Node2->prev;` `    ``Node2->prev = temp;`   `    ``if` `(Node1->prev != NULL)` `        ``Node1->prev->next = Node1;` `    ``if` `(Node2->prev != NULL)` `        ``Node2->prev->next = Node2;` `}`   `// Driver Code` `int` `main()` `{`   `    ``Node* head = NULL;` `    ``Node* tail = NULL;`   `    ``push(head, tail, 1);` `    ``push(head, tail, 8);` `    ``push(head, tail, 7);` `    ``push(head, tail, 9);` `    ``push(head, tail, 4);`   `    ``int` `X = 1, Y = 4;`   `    ``cout << ``"Before Swapping: "``;` `    ``print(head);`   `    ``swap(head, tail, X, Y);` `    ``cout << ``"After Swapping: "``;` `    ``print(head);`   `    ``return` `0;` `}`

Java

 `// Java code to implement the above approach` `import` `java.util.*;`   `class` `GFG{`   `// Link list Node Class` `static` `class` `Node {`   `    ``int` `data;` `    ``Node prev;` `    ``Node next;`   `    ``// Constructor function` `    ``Node(``int` `data)` `    ``{` `        ``this``.data = data;` `        ``this``.prev = ``null``;` `        ``this``.next = ``null``;` `    ``}` `};` `static` `class` `pair` `{ ` `    ``Node first, second; ` `    ``public` `pair(Node first, Node second)  ` `    ``{ ` `        ``this``.first = first; ` `        ``this``.second = second; ` `    ``}    ` `} `   `// Function to print linked list` `static` `void` `print(Node head)` `{` `    ``Node temp = head;`   `    ``// Iterate until node is NOT null` `    ``while` `(temp != ``null``) {` `        ``System.out.print(temp.data+ ``" "``);` `        ``temp = temp.next;` `    ``}` `    ``System.out.println();` `}` `static` `Node head;` `static` `Node tail;` `// Function to push a node in DLL` `static` `void` `push( ``int` `item)` `{`   `    ``// DLL is empty` `    ``if` `(tail == ``null``) {`   `        ``Node temp = ``new` `Node(item);` `        ``tail = temp;` `        ``head = temp;` `    ``}`   `    ``// DLL is not empty` `    ``else` `{` `        ``Node temp = ``new` `Node(item);` `        ``tail.next = temp;` `        ``temp.prev = tail;` `        ``tail = temp;` `    ``}` `}`   `// Function to find the nodes` `// which have to be swapped` `static` `pair find(``int` `x, ``int` `y)` `{` `    ``Node N1 = ``null``;` `    ``Node N2 = ``null``;` `    ``Node temp = head;`   `    ``// Traversing the list` `    ``while` `(temp != ``null``) {` `        ``if` `(temp.data == x)` `            ``N1 = temp;` `        ``else` `if` `(temp.data == y)` `            ``N2 = temp;` `        ``temp = temp.next;` `    ``}` `    ``return` `new` `pair(N1, N2);` `}`   `// Function to swap the nodes` `// consisting of x and y` `static` `void` `swap( ``int` `x, ``int` `y)` `{`   `    ``// Edge Cases` `    ``if` `(head == ``null` `|| head.next == ``null` `        ``|| x == y)` `        ``return``;`   `    ``// Finding the Nodes` `    ``pair p = find( x, y);`   `    ``Node Node1 = p.first;` `    ``Node Node2 = p.second;`   `    ``if` `(Node1 == head)` `        ``head = Node2;` `    ``else` `if` `(Node2 == head)` `        ``head = Node1;` `    ``if` `(Node1 == tail)` `        ``tail = Node2;` `    ``else` `if` `(Node2 == tail)` `        ``tail = Node1;`   `    ``// Swapping Node1 and Node2` `    ``Node temp;` `    ``temp = Node1.next;` `    ``Node1.next = Node2.next;` `    ``Node2.next = temp;`   `    ``if` `(Node1.next != ``null``)` `        ``Node1.next.prev = Node1;` `    ``if` `(Node2.next != ``null``)` `        ``Node2.next.prev = Node2;`   `    ``temp = Node1.prev;` `    ``Node1.prev = Node2.prev;` `    ``Node2.prev = temp;`   `    ``if` `(Node1.prev != ``null``)` `        ``Node1.prev.next = Node1;` `    ``if` `(Node2.prev != ``null``)` `        ``Node2.prev.next = Node2;` `}`   `// Driver Code` `public` `static` `void` `main(String[] args)` `{`   `    ``head = ``null``;` `    ``tail = ``null``;`   `    ``push( ``1``);` `    ``push( ``8``);` `    ``push(``7``);` `    ``push(``9``);` `    ``push( ``4``);`   `    ``int` `X = ``1``, Y = ``4``;`   `    ``System.out.print(``"Before Swapping: "``);` `    ``print(head);`   `    ``swap( X, Y);` `    ``System.out.print(``"After Swapping: "``);` `    ``print(head);` `}` `}`   `// This code is contributed by shikhasingrajput`

Python3

 `# Python code to implement the above approach`   `# Link list Node Class` `class` `Node:` `    ``def` `__init__(``self``, data):` `        ``self``.data ``=` `data` `        ``self``.prev ``=` `None` `        ``self``.``next` `=` `None`   `class` `pair:` `    ``def` `__init__(``self``, first, second):` `        ``self``.first ``=` `first` `        ``self``.second ``=` `second`   `class` `DoublyLL:` `    ``def` `__init__(``self``):` `        ``self``.head ``=` `None` `        ``self``.tail ``=` `None`   `    ``# Function to print linked list` `    ``def` `print_list(``self``):` `        ``temp ``=` `self``.head` `        ``while` `temp:` `            ``print``(temp.data, end``=``" "``)` `            ``temp ``=` `temp.``next` `        ``print``()`   `    ``# Function to push a node in DLL` `    ``def` `push(``self``, item):`   `        ``# DLL is empty` `        ``if` `self``.tail ``=``=` `None``:` `            ``temp ``=` `Node(item)` `            ``self``.tail ``=` `temp` `            ``self``.head ``=` `temp` `        ``# DLL is not empty` `        ``else``:` `            ``temp ``=` `Node(item)` `            ``self``.tail.``next` `=` `temp` `            ``temp.prev ``=` `self``.tail` `            ``self``.tail ``=` `temp`   `    ``# Function to find the nodes` `    ``# which have to be swapped` `    ``def` `find(``self``, x, y):` `        ``N1 ``=` `None` `        ``N2 ``=` `None` `        ``temp ``=` `self``.head`   `        ``# Traversing the list` `        ``while` `temp !``=` `None``:` `            ``if` `temp.data ``=``=` `x:` `                ``N1 ``=` `temp` `            ``elif` `temp.data ``=``=` `y:` `                ``N2 ``=` `temp` `            ``temp ``=` `temp.``next`   `        ``return` `pair(N1, N2)`   `    ``# Function to swap the nodes` `    ``# consisting of x and y` `    ``def` `swap(``self``, x, y):`   `        ``# Edge Cases` `        ``if` `self``.head ``=``=` `None` `or` `self``.head.``next` `=``=` `None` `or` `x ``=``=` `y:` `            ``return`   `        ``# Finding the Nodes` `        ``p ``=` `self``.find(x, y)` `        ``Node1 ``=` `p.first` `        ``Node2 ``=` `p.second`   `        ``if` `Node1 ``=``=` `self``.head:` `            ``self``.head ``=` `Node2` `        ``elif` `Node2 ``=``=` `self``.head:` `            ``self``.head ``=` `Node1` `        ``if` `Node1 ``=``=` `self``.tail:` `            ``self``.tail ``=` `Node2` `        ``elif` `Node2 ``=``=` `self``.tail:` `            ``self``.tail ``=` `Node1`   `        ``# Swapping Node1 and Node2` `        ``temp ``=` `None` `        ``temp ``=` `Node1.``next` `        ``Node1.``next` `=` `Node2.``next` `        ``Node2.``next` `=` `temp`   `        ``if` `Node1.``next` `!``=` `None``:` `            ``Node1.``next``.prev ``=` `Node1` `        ``if` `Node2.``next` `!``=` `None``:` `            ``Node2.``next``.prev ``=` `Node2`   `        ``temp ``=` `Node1.prev` `        ``Node1.prev ``=` `Node2.prev` `        ``Node2.prev ``=` `temp`   `        ``if` `Node1.prev !``=` `None``:` `            ``Node1.prev.``next` `=` `Node1` `        ``if` `Node2.prev !``=` `None``:` `            ``Node2.prev.``next` `=` `Node2`     `# Driver Code` `if` `__name__ ``=``=` `'__main__'``:`   `    ``dll ``=` `DoublyLL()`   `    ``dll.push(``1``)` `    ``dll.push(``8``)` `    ``dll.push(``7``)` `    ``dll.push(``9``)` `    ``dll.push(``4``)`   `    ``X ``=` `1` `    ``Y ``=` `4`   `    ``print``(``"Before Swapping:"``, end``=``" "``)` `    ``dll.print_list()`   `    ``dll.swap(X, Y)`   `    ``print``(``"After Swapping:"``, end``=``" "``)` `    ``dll.print_list()`   `# This code is contributed by Tapesh (tapeshdua420)`

C#

 `// C# code to implement the above approach` `using` `System;`   `public` `class` `GFG{`   `// Link list Node Class` `class` `Node {`   `    ``public` `int` `data;` `    ``public` `Node prev;` `    ``public` `Node next;`   `    ``// Constructor function` `    ``public` `Node(``int` `data)` `    ``{` `        ``this``.data = data;` `        ``this``.prev = ``null``;` `        ``this``.next = ``null``;` `    ``}` `};` `class` `pair` `{ ` `    ``public` `Node first, second; ` `    ``public` `pair(Node first, Node second)  ` `    ``{ ` `        ``this``.first = first; ` `        ``this``.second = second; ` `    ``}    ` `} `   `// Function to print linked list` `static` `void` `print(Node head)` `{` `    ``Node temp = head;`   `    ``// Iterate until node is NOT null` `    ``while` `(temp != ``null``) {` `        ``Console.Write(temp.data+ ``" "``);` `        ``temp = temp.next;` `    ``}` `    ``Console.WriteLine();` `}` `static` `Node head;` `static` `Node tail;` `// Function to push a node in DLL` `static` `void` `push( ``int` `item)` `{`   `    ``// DLL is empty` `    ``if` `(tail == ``null``) {`   `        ``Node temp = ``new` `Node(item);` `        ``tail = temp;` `        ``head = temp;` `    ``}`   `    ``// DLL is not empty` `    ``else` `{` `        ``Node temp = ``new` `Node(item);` `        ``tail.next = temp;` `        ``temp.prev = tail;` `        ``tail = temp;` `    ``}` `}`   `// Function to find the nodes` `// which have to be swapped` `static` `pair find(``int` `x, ``int` `y)` `{` `    ``Node N1 = ``null``;` `    ``Node N2 = ``null``;` `    ``Node temp = head;`   `    ``// Traversing the list` `    ``while` `(temp != ``null``) {` `        ``if` `(temp.data == x)` `            ``N1 = temp;` `        ``else` `if` `(temp.data == y)` `            ``N2 = temp;` `        ``temp = temp.next;` `    ``}` `    ``return` `new` `pair(N1, N2);` `}`   `// Function to swap the nodes` `// consisting of x and y` `static` `void` `swap( ``int` `x, ``int` `y)` `{`   `    ``// Edge Cases` `    ``if` `(head == ``null` `|| head.next == ``null` `        ``|| x == y)` `        ``return``;`   `    ``// Finding the Nodes` `    ``pair p = find( x, y);`   `    ``Node Node1 = p.first;` `    ``Node Node2 = p.second;`   `    ``if` `(Node1 == head)` `        ``head = Node2;` `    ``else` `if` `(Node2 == head)` `        ``head = Node1;` `    ``if` `(Node1 == tail)` `        ``tail = Node2;` `    ``else` `if` `(Node2 == tail)` `        ``tail = Node1;`   `    ``// Swapping Node1 and Node2` `    ``Node temp;` `    ``temp = Node1.next;` `    ``Node1.next = Node2.next;` `    ``Node2.next = temp;`   `    ``if` `(Node1.next != ``null``)` `        ``Node1.next.prev = Node1;` `    ``if` `(Node2.next != ``null``)` `        ``Node2.next.prev = Node2;`   `    ``temp = Node1.prev;` `    ``Node1.prev = Node2.prev;` `    ``Node2.prev = temp;`   `    ``if` `(Node1.prev != ``null``)` `        ``Node1.prev.next = Node1;` `    ``if` `(Node2.prev != ``null``)` `        ``Node2.prev.next = Node2;` `}`   `// Driver Code` `public` `static` `void` `Main(String[] args)` `{`   `    ``head = ``null``;` `    ``tail = ``null``;`   `    ``push( 1);` `    ``push( 8);` `    ``push(7);` `    ``push(9);` `    ``push( 4);`   `    ``int` `X = 1, Y = 4;`   `    ``Console.Write(``"Before Swapping: "``);` `    ``print(head);`   `    ``swap( X, Y);` `    ``Console.Write(``"After Swapping: "``);` `    ``print(head);` `}` `}`       `// This code contributed by shikhasingrajput`

Javascript

 ``

Output

```Before Swapping: 1 8 7 9 4
After Swapping: 4 8 7 9 1 ```

Time Complexity: O(N)
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up
Recommended Articles
Page :