Reverse a Linked-list. Write code in C.


Question : Reverse a Linked-list. Write code in C.

Answer: There are multiple ways to go about this. Let’s first look at a recursive solution.
 
Node * reverse( Node * ptr , Node * previous)
{
    Node * temp;
    if(ptr->next == NULL) {
        ptr->next = previous;
        return ptr;
    } else {
        temp = reverse(ptr->next, ptr);
        ptr->next = previous;
        return temp;
    }
}
reversedHead = reverse(head, NULL);

Now for a non-recursive solution.

 
Node * reverse( Node * ptr )
{
    Node * temp;
    Node * previous = NULL;
    while(ptr != NULL) {
        temp = ptr->next;
        ptr->next = previous;
        previous = ptr;
        ptr = temp;
    }
    return previous;
}
 

If anyone has any modifications or a better methods, please post it up. Comments are always welcome.

Comments

Popular posts from this blog

AGRICULTURAL SCIENTIST RECRUITMENT BOARD

CIVIL SERVICES' (I.A.S.) EXAMINATION

HSC Exam Time Table 2013 Arts, Commerce, Science