Tuesday, February 11, 2014

Pairwise swap nodes of a given linked list.

void pairWiseSwap(Node *&head)
{
    if (head == NULL || head->next == NULL)
        return;

    Node *prev = head;
    Node *curr = head->next;

    head = curr;

    while (1)
    {
        Node *next = curr->next;
        curr->next = prev;

        if (next == NULL || next->next == NULL)
        {
            prev->next = next;
            break;
        }

        prev->next = next->next;
        prev = next;
        curr = prev->next;
    }
}

1 comment: