Web Toolbar by Wibiya

Pages

Sunday, January 22, 2012

Reverse a linked list.

Solution #1: Iterative approach to reverse a linked list,

void itrReverse(struct node** head)
{
    if(*head == NULL)
        return;

    struct node* prev = NULL;
    struct node* curr = *head;
    struct node* next = curr->next;

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

        if(next == NULL)
            break;

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

    *head = curr;
}

Solution #2: Recursive approach to reverse a linked list,

void recReverse(struct node** head)
{
    struct node* first;
    struct node* rest;

    if(*head == NULL)
        return;

    first = *head;
    rest = first->next;

    if(rest == NULL)
        return;

    recReverse(&rest);

    first->next->next = first;
    first->next = NULL;

    *head = rest;
}
 

2 comments:

Supraja said...

Nice blog.. v. useful :) all the best..

Suchit Maindola said...

Thank you :)