Thursday, 27 September 2018

09 Insert a new node before a particular node in LInked List

         Insert a new node before a particular node
                                          
                              
             

Figure 5. Insert node before a  Node.

Logic:
Before calling insert_before function in main call search function and find out nxt pointer by equating data.
Prepare a new_node of desired data and cursor->next pointer
Then assign cursor->next to new_node.  

Main Function code:
node* nxt=NULL;
printf("\n Enter data of  node before which you want to add a node:");
scanf("%d",&data);

nxt=search(head,data);
printf("\n Enter data for adding a new node before a node:");
scanf("%d",&data);
head=insert_before(head,data,nxt);
display(head);

C function for insert before function:-
node* insert_before(node *head, int data, node* nxt)
{
    if(nxt == NULL || head == NULL)
        return NULL;
     if(head == nxt)      //If nxt node is head then simply prepend the data
    {
        head = prepend(head,data);
        return head;
    }
// search previous pointer by equating cursor->next with nxt
    node *cursor = head;
    while(cursor != NULL)
    {
        if(cursor->next == nxt)
            break;
        cursor = cursor->next;
    }
 //if cursor is not NULL then create a node having create(data,cursor->next)
    if(cursor != NULL)
    {
        node* new_node = create(data,cursor->next);
        cursor->next = new_node;
        return head;
    }
    else
    {
        return NULL;
    }
}
       

No comments:

Post a Comment