Thursday, 27 September 2018

13. Reverse linked list

13. Reverse linked list:-
Logic :
Assign current pointer to head and traverse linked list till NULL.
assign Next pointer of head to Null.
Just reverse all the link of next nodes.
finally at last node assign last node as a head.

Main Function code:
head=reverse(head);
display(head);

C function for reverse linked list:
node* reverse(node* head)
{
    node* prev    = NULL;
    node* current = head;
    node* next;
    while (current != NULL) //  traverse linked list using current pointer
    {
        next  = current->next; // update next 
        current->next = prev; //update current next i.e. reverse the link
        prev = current;   // update prev
        current = next;   // update current
    }
    head = prev; //finally assign last node as a head
    return head;


}

No comments:

Post a Comment