Sunday, July 11, 2010

Delete a node from singly linked list. Keep following condition in mind...?

I need to delete a node from a singly linked list.


I've been provided just the address of the node to be deleted and no other information, no head node pointer and no previous node pointer.


Is it possible to delete this node..If yes, please explain approach/algorithm or pseudo code will be highly appreciated.





Thanks in advance

Delete a node from singly linked list. Keep following condition in mind...?
You can't without knowing what points to this node. If you don't modify the previous node or head, you will break the list.





The one possibility is if the list is circular (i.e. the last node points back to the head). In the case, you can find the head and the previous node if any by traversing the entire list. Still, it's a horribly expensive way to delete a list node. This defeats the biggest benefit of linked lists - constant time inserts and deletes.





Another possibility is to use a deleted flag. When deleting, you don't actually delete the node, just mark it. When processing the list, skip the nodes marked as deleted. Like the idea above, this ignores the great advantage of linked lists. It's so easy to delete a node, there is no reason to keep an unneeded item.





If you need to delete with only having a node pointer, you should use a doubly linked list. Then you know all the pointers that need to be modified.
Reply:Yes,u can Delete that node.


U can access the next node right.


copy the next node data into the current node and same the address


now both nodes are pointing to the same node and both contain same data.


Now Delete the current nodes next node. Report It



No comments:

Post a Comment