Linked List - Swap nodes

Swap nodes in a linked list without swapping the data

Sample input: swap 2 and 9 in 1->5->2->3->9->4

Sample output: 1->5->9->3->2->4

Steps:

1) find X,Y in the list and also their previous nodes.
2) prevX.next = Y and prevY.next = X
3) temp = X.next , X.next = Y.next, Y.next = temp

Code:


void swapNodes(int x, int y){


        Node prevX = null, X = head;
        while (X != null && X.data != x)
        {
            prevX = X;
            X = X.next;
        }

        Node prevY = null, Y = head;
        while (Y != null && Y.data != y)
        {
            prevY = Y;
            Y = Y.next;
        }

        if (prevX != null)

            prevX.next = Y;
        else 
            head = Y;

        if (prevY != null)
            prevY.next = X;
        else 
            head = X;

        Node temp = X.next;
        X.next = Y.next;
        Y.next = temp;
    }


Illustration:

Example (i):
swap 2 and 9 in 1->5->2->3->9->4

Find prevX,X,prevY,Y


prevX.next = Y

prevY.next = X


temp = X.next
X.next = Y.next


X.next = temp

Result:

Example (ii): (one of the node is head node)

Swap 1 and 2 in 1->2->3->4->5

Find X and Y and their prev nodes

Since prevX = null, head=Y

prevY.next = X


swap next nodes of x and y

                  Happy New Year :)








Comments

Popular posts from this blog

Tree traversals - Inorder Traversal

Binary Search tree (Insertion)

Stack implementation using array