Advanced

Node Swapping

How Node Swapping Works

To swap two nodes by changing links:

  1. Find currX and prevX
  2. Find currY and prevY
  3. If either not found โ†’ return
  4. Link prevX โ†’ currY (or update head)
  5. Link prevY โ†’ currX (or update head)
  6. Swap their next pointers

Before Swap

10
โ†’
20
โ†’
30
โ†’
40
โ†’
50
โ†’NULL

20 and 40 highlighted for swap

After Swap

10
โ†’
40
โ†’
30
โ†’
20
โ†’
50
โ†’NULL

โœ“ Nodes swapped by links

node-swapping
#include <iostream>
using namespace std;

class Node {
public:
    int data;
    Node* next;
};

class LinkedList {
private:
    Node* head;

public:
    LinkedList() {
        head = NULL;
    }

    void insertEnd(int value) {
        Node* newNode = new Node();
        newNode->data = value;
        newNode->next = NULL;

        if (head == NULL) {
            head = newNode;
            return;
        }

        Node* temp = head;
        while (temp->next != NULL) {
            temp = temp->next;
        }
        temp->next = newNode;
    }

    // โ˜… SWAP NODES by changing LINKS (not data) โ˜…
    void swapNodes(int x, int y) {
        if (x == y) return;

        // Find node x and its previous
        Node* prevX = NULL;
        Node* currX = head;
        while (currX != NULL && currX->data != x) {
            prevX = currX;
            currX = currX->next;
        }

        // Find node y and its previous
        Node* prevY = NULL;
        Node* currY = head;
        while (currY != NULL && currY->data != y) {
            prevY = currY;
            currY = currY->next;
        }

        // If either x or y not found
        if (currX == NULL || currY == NULL) {
            cout << "One or both values not found!" << endl;
            return;
        }

        // If x is not head, link prevX to currY
        if (prevX != NULL)
            prevX->next = currY;
        else
            head = currY;

        // If y is not head, link prevY to currX
        if (prevY != NULL)
            prevY->next = currX;
        else
            head = currX;

        // Swap next pointers
        Node* temp = currY->next;
        currY->next = currX->next;
        currX->next = temp;
    }

    void display() {
        Node* temp = head;
        while (temp != NULL) {
            cout << temp->data << " -> ";
            temp = temp->next;
        }
        cout << "NULL" << endl;
    }
};

int main() {
    LinkedList list;
    list.insertEnd(10);
    list.insertEnd(20);
    list.insertEnd(30);
    list.insertEnd(40);
    list.insertEnd(50);

    cout << "Before swap:" << endl;
    list.display();
    // 10 -> 20 -> 30 -> 40 -> 50 -> NULL

    list.swapNodes(20, 40);

    cout << "After swapping 20 and 40:" << endl;
    list.display();
    // 10 -> 40 -> 30 -> 20 -> 50 -> NULL

    return 0;
}