Thursday, 27 September 2018

11.Delete a node from the back of the linked list

11. Delete a node from the back of the linked list
Figure 7. Delete back Node.

Logic:
Traverse the whole linked list till cursor->next not equal to NULL
before  cursor->next makes equal to NULL  mark the pointer as a back 
then make back->next =NULL and free last node i.e.cursor

Main function code:
head=remove_back(head);
display(head);

C function for remove back:- 
node* remove_back(node* head)
{
 if(head == NULL)
 return NULL;
 node *cursor = head;
 node *back = NULL;
 while(cursor->next != NULL) // find out back pointer which points to second last node
{
    back = cursor;
    cursor = cursor->next;
   }
    if(back != NULL)
        back->next = NULL;
     // if this is the last node in the list
    if(cursor == head)
        head = NULL;

    free(cursor); 
     return head;   
}

No comments:

Post a Comment