Sunday, October 14, 2012

Swap every 2 nodes of a Linked List


// INPUT : a->b->c->d->e->f
// OUTPUT : b->a->d->c->f->e

void swapAdjacent(Node **headRef){
    Node *curr = *headRef;
    Node *prev = NULL;
    Node *currNext;
    if(curr == NULL){
        return;
    }
    while(curr->next != NULL){
        currNext = curr->next;
        curr->next = currNext->next;
        currNext->next = curr;
        if(*headRef == curr){
            *headRef = currNext;
        } else {
            prev->next = currNext;
        }
        if(curr->next != NULL){
            prev = curr;
            curr = curr->next;
        }
    }
}

No comments:

Post a Comment