top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Given only a pointer to a node to be deleted in a singly linked list, how do you delete it?

+3 votes
731 views
Given only a pointer to a node to be deleted in a singly linked list, how do you delete it?
posted Apr 15, 2014 by Atul Mishra

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button
Delete the next node of this node (which is simple), copy the data of the next node to this node and you are done...

1 Answer

+2 votes

As per the Salil's Suggestion:

Algorithm:
Delete the next node of this node (which is simple), copy the data of the next node to this node

Code

void deleteNode(struct node *node_ptr)
{
   struct node *temp = node_ptr->next; // Pick the next node
   node_ptr->data    = temp->data; // Copy the next node data to this node 
   node_ptr->next    = temp->next; // Align pointers 
   free(temp); // Delete the next node
}
answer Apr 15, 2014 by anonymous
There is one limitation in this problem. Node to be deleted  must not be the last one.
Good catch...may be traversing is better foolproof but costly approach.
...