Swap nodes in a linked list without swapping data

Given a singly linked list with two value x and y, the task is to swap two nodes having values x and y without swapping data.
Swap nodes in a linked list without swapping data
Examples:Â
Input: 10->15->12->13->20->14, Â x = 12, y = 20
Output: 10->15->20->13->12->14Input: 10->15->12->13->20->14, Â x = 10, y = 20
Output: 20->15->12->13->10->14Input: 10->15->12->13->20->14, Â x = 12, y = 13
Output: 10->15->13->12->20->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:
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 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 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++
/* This program swaps the nodes of linked list ratherthan 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 bychanging 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 of 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 program to test above function */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 << "\nLinked list after calling swapNodes() ";    printList(start);Â
    return 0;}Â
// This is code is contributed by rathbhupendra |
C
/* This program swaps the nodes of linked list rather   than swapping the field from the nodes.*/Â
#include <stdio.h>#include <stdlib.h>Â
/* A linked list node */struct Node {Â Â Â Â int data;Â Â Â Â struct Node* next;};Â
/* Function to swap nodes x and y in linked list by   changing links */void swapNodes(struct 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    struct 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    struct 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    struct Node* temp = currY->next;    currY->next = currX->next;    currX->next = temp;}Â
/* Function to add a node at the beginning of List */void push(struct Node** head_ref, int new_data){    /* allocate node */    struct Node* new_node        = (struct Node*)malloc(sizeof(struct Node));Â
    /* put in the data */    new_node->data = new_data;Â
    /* link the old list of 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(struct Node* node){Â Â Â Â while (node != NULL) {Â Â Â Â Â Â Â Â printf("%d ", node->data);Â Â Â Â Â Â Â Â node = node->next;Â Â Â Â }}Â
/* Driver program to test above function */int main(){Â Â Â Â struct 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);Â
    printf("\n Linked list before calling swapNodes() ");    printList(start);Â
    swapNodes(&start, 4, 3);Â
    printf("\n Linked list after calling swapNodes() ");    printList(start);Â
    return 0;} |
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 {Â Â Â Â Node head; // head of listÂ
    /* 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 program to test above function */    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(            "\n Linked list before calling swapNodes() ");        llist.printList();Â
        llist.swapNodes(4, 3);Â
        System.out.print(            "\n Linked list after calling swapNodes() ");        llist.printList();    }}// This code is contributed by Rajat Mishra |
Python
# Python program to swap two given nodes of a linked listclass LinkedList(object):Â Â Â Â def __init__(self):Â Â Â Â Â Â Â Â self.head = NoneÂ
    # head of list    class Node(object):        def __init__(self, d):            self.data = d            self.next = NoneÂ
    # Function to swap Nodes x and y in linked list by    # changing links    def swapNodes(self, x, y):Â
        # Nothing to do if x and y are same        if x == y:            returnÂ
        # Search for x (keep track of prevX and CurrX)        prevX = None        currX = self.head        while currX != None and currX.data != x:            prevX = currX            currX = currX.nextÂ
        # Search for y (keep track of prevY and currY)        prevY = None        currY = self.head        while currY != None and currY.data != y:            prevY = currY            currY = currY.nextÂ
        # If either x or y is not present, nothing to do        if currX == None or currY == None:            return        # If x is not head of linked list        if prevX != None:            prevX.next = currY        else: # make y the new head            self.head = currYÂ
        # If y is not head of linked list        if prevY != None:            prevY.next = currX        else: # make x the new head            self.head = currXÂ
        # Swap next pointers        temp = currX.next        currX.next = currY.next        currY.next = tempÂ
    # Function to add Node at beginning of list.    def push(self, new_data):Â
        # 1. alloc the Node and put the data        new_Node = self.Node(new_data)Â
        # 2. Make next of new Node as head        new_Node.next = self.headÂ
        # 3. Move the head to point to new Node        self.head = new_NodeÂ
    # This function prints contents of linked list starting    # from the given Node    def printList(self):        tNode = self.head        while tNode != None:            print tNode.data,            tNode = tNode.nextÂ
Â
# Driver program to test above functionllist = LinkedList()Â
# The constructed linked list is:# 1->2->3->4->5->6->7llist.push(7)llist.push(6)llist.push(5)llist.push(4)llist.push(3)llist.push(2)llist.push(1)print "Linked list before calling swapNodes() "llist.printList()llist.swapNodes(4, 3)print "\nLinked list after calling swapNodes() "llist.printList()Â
# This code is contributed by BHAVYA JAIN |
C#
// C# program to swap two given// nodes of a linked listusing System;Â
class Node {Â Â Â Â public int data;Â Â Â Â public Node next;Â Â Â Â public Node(int d)Â Â Â Â {Â Â Â Â Â Â Â Â data = d;Â Â Â Â Â Â Â Â next = null;Â Â Â Â }}Â
public class LinkedList {Â Â Â Â Node head; // head of listÂ
    /* 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) {            Console.Write(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);Â
        Console.Write(            "\n Linked list before calling swapNodes() ");        llist.printList();Â
        llist.swapNodes(4, 3);Â
        Console.Write(            "\n Linked list after calling swapNodes() ");        llist.printList();    }}Â
// This code is contributed by 29AjayKumar |
Javascript
<script>Â
// JavaScript program to swap two // given nodes of a linked listÂ
class Node {Â Â Â Â constructor(val) {Â Â Â Â Â Â Â Â this.data = val;Â Â Â Â Â Â Â Â this.next = null;Â Â Â Â }}var head; // head of listÂ
    /*     Function to swap Nodes x and y in      linked list by changing links     */     function swapNodes(x , y) {        // Nothing to do if x and y are same        if (x == y)            return;Â
        // Search for x (keep track of prevX and CurrX)       var prevX = null, currX = head;        while (currX != null && currX.data != x) {            prevX = currX;            currX = currX.next;        }Â
        // Search for y (keep track of prevY and currY)        var 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        var temp = currX.next;        currX.next = currY.next;        currY.next = temp;    }Â
    /* Function to add Node at beginning of list. */     function push(new_data) {        /* 1. alloc the Node and put the data */var 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     */     function printList() {       var tNode = head;        while (tNode != null) {            document.write(tNode.data + " ");            tNode = tNode.next;        }    }Â
    /* Driver program to test above function */     Â
        /*         The constructed linked list is:         1->2->3->4->5->6->7         */        push(7);        push(6);        push(5);        push(4);        push(3);        push(2);        push(1);Â
        document.write(        " Linked list before calling swapNodes()<br/> ")        ;        printList();Â
        swapNodes(4, 3);Â
        document.write(        "<br/> Linked list after calling swapNodes() <br/>"        );        printList();Â
// This code is contributed by todaysgauravÂ
</script> |
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)Â
Efficient Approach:
The above code can be optimized to search x and y in a single traversal. Two loops are used to keep the program simple.
Below is the implementation of the above approach:
C++
// C++ program to swap two given nodes of a linked list#include <iostream>using namespace std;Â
// A linked list node classclass 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 Listvoid 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 codeint 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();}Â
// This code is contributed by Sania Kumari Gupta// (kriSania804) |
C
// C program to swap two given nodes of a linked list#include <stdio.h>#include <stdlib.h>Â
/* A linked list node */typedef struct Node {Â Â Â Â int data;Â Â Â Â struct Node* next;} Node;Â
/* Function to add a node at the beginning of List */void push(struct Node** head_ref, int new_data){    /* allocate node */    Node* new_node = (Node*)malloc(sizeof(struct Node));     /* put in the data */    new_node->data = new_data;     /* link the old list of 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) {Â Â Â Â Â Â Â Â printf("%d ", node->data);Â Â Â Â Â Â Â Â node = node->next;Â Â Â Â }}Â
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 codeint main(){Â Â Â Â struct 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);Â
    printf("Linked list before calling swapNodes() ");    printList(start);    printf("\n");Â
    swapNodes(&start, 6, 1);Â
    printf("Linked list after calling swapNodes() ");    printList(start);}Â
// This code is contributed by Sania Kumari Gupta// (kriSania804) |
Java
// Java program to swap two given nodes of a linked listpublic 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();    }} |
Python3
# Python3 program to swap two given# nodes of a linked listÂ
# A linked list node classÂ
Â
class Node:Â
    # constructor    def __init__(self, val=None, next1=None):        self.data = val        self.next = next1Â
    # print list from this    # to last till None    def printList(self):Â
        node = selfÂ
        while (node != None):            print(node.data, end=" ")            node = node.next        print(" ")Â
# Function to add a node# at the beginning of ListÂ
Â
def push(head_ref, new_data):Â
    # allocate node    (head_ref) = Node(new_data, head_ref)    return head_refÂ
Â
def swapNodes(head_ref, x, y):Â Â Â Â head = head_refÂ
    # Nothing to do if x and y are same    if (x == y):        return NoneÂ
    a = None    b = NoneÂ
    # search for x and y in the linked list    # and store their pointer in a and b    while (head_ref.next != None):Â
        if ((head_ref.next).data == x):            a = head_refÂ
        elif ((head_ref.next).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 != None and b != None):        temp = a.next        a.next = b.next        b.next = temp        temp = a.next.next        a.next.next = b.next.next        b.next.next = tempÂ
    return headÂ
# Driver codeÂ
Â
start = NoneÂ
# The constructed linked list is:# 1.2.3.4.5.6.7start = push(start, 7)start = push(start, 6)start = push(start, 5)start = push(start, 4)start = push(start, 3)start = push(start, 2)start = push(start, 1)Â
print("Linked list before calling swapNodes() ")start.printList()Â
start = swapNodes(start, 6, 1)Â
print("Linked list after calling swapNodes() ")start.printList()Â
# This code is contributed by Arnab Kundu |
C#
// C# program to swap two// given nodes of a linked listusing System;Â
class GFG {    // A linked list node class    public class Node {Â
        public int data;        public Node next;Â
        // constructor        public Node(int val, Node next1)        {            data = val;            next = next1;        }Â
        // print list from this        // to last till null        public void printList()        {Â
            Node node = this;Â
            while (node != null) {                Console.Write(node.data + " ");                node = node.next;            }            Console.WriteLine();        }    }Â
    // Function to add a node    // at the beginning of List    static Node push(Node head_ref, int new_data)    {Â
        // allocate node        (head_ref) = new Node(new_data, head_ref);        return head_ref;    }Â
    static Node swapNodes(Node head_ref, int x, int y)    {        Node head = head_ref;Â
        // Nothing to do if x and y are same        if (x == y)            return null;Â
        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.next != null) {Â
            if ((head_ref.next).data == x) {                a = head_ref;            }Â
            else if ((head_ref.next).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 != null && b != null) {            Node temp = a.next;            a.next = b.next;            b.next = temp;            temp = a.next.next;            a.next.next = b.next.next;            b.next.next = temp;        }        return head;    }Â
    // Driver code    public static void Main()    {Â
        Node start = null;Â
        // The constructed linked list is:        // 1.2.3.4.5.6.7        start = push(start, 7);        start = push(start, 6);        start = push(start, 5);        start = push(start, 4);        start = push(start, 3);        start = push(start, 2);        start = push(start, 1);Â
        Console.Write(            "Linked list before calling swapNodes() ");        start.printList();Â
        start = swapNodes(start, 6, 1);Â
        Console.Write(            "Linked list after calling swapNodes() ");        start.printList();    }}Â
/* This code contributed by PrinciRaj1992 */ |
Javascript
<script>// javascript program to swap two given nodes of a linked listÂ
    // Represent a node of the singly linked list     class Node {            constructor(val) {                this.data = val;                this.next = null;            }        }      Â
    // Represent the head and tail of the singly linked list     var head = null;     var tail = null;Â
    // addNode() will add a new node to the list     function addNode(data) {        // Create a new nodevar 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     function swap(n1 , n2) {var 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    var temp = node1.next;            node1.next = node2.next;            node2.next = temp;        } else {            document.write("Swapping is not possible");        }    }Â
    // display() will display all the    // nodes present in the list     function display() {        // Node current will point to headvar current = head;Â
        if (head == null) {            document.write("List is empty");            return;        }        while (current != null) {            // Prints each node by incrementing pointer            document.write(current.data + " ");            current = current.next;        }        document.write();    }Â
     Â
             // Add nodes to the list        addNode(1);        addNode(2);        addNode(3);        addNode(4);        addNode(5);        addNode(6);        addNode(7);Â
        document.write("Original list:<br/> ");        display();Â
        // Swaps the node 2 with node 5        swap(6, 1);Â
        document.write("<br/>List after swapping nodes: <br/>");        display();Â
// This code contributed by aashish1995</script> |
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)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



