Swap nodes in a linked list

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 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

x and y may or may not be adjacent. Either x or y may be a head node. Either x or y may be a tail node. x or/and y may not be present in the linked list.

Solution:

  1. The idea it to first search x and y in given linked list. If any of them is not present, then return.
  2. While searching for x and y, keep track of current and previous pointers.
  3. First change next of previous pointers, then change next of current pointers.
Node * LinkedList::swapNodes(Node *head, int x, int y) {
    // Step 1: find x and y
    Node *xPrev = NULL, *xCur = head;
    while (xCur && xCur->data != x) {
        xPrev = xCur;
        xCur = xCur->next;
    }

    Node *yPrev = NULL, *yCur = head;
    while (yCur && yCur->data != y) {
        yPrev = yCur;
        yCur = yCur->next;
    }

    // Step 2: swap
    if (!xCur || !yCur) return head;

    // If x is not head of linked list
    if (xPrev != NULL) {
        xPrev->next = yCur;
    } else { // Else make y as new head
        head = yCur;
    }

    // If y is not head of linked list
    if (yPrev != NULL) {
        yPrev->next = xCur;
    } else {  // Else make x as new head
        head = xCur;
    }

    // Swap next pointers
    struct Node *temp = yCur->next;
    yCur->next = xCur->next;
    xCur->next = temp;

    return head;
}

results matching ""

    No results matching ""