Raj said:
Thanks all of u for the replies....
The suggestion is working out....But as Howard said the logic does not
work if the node to be deleted is the last one.
Any solutions??
Nope. If the node to be deleted is the last one, then you're stuck. You
should not delete it, because then you may at some point access it illegally
through the next pointer of the previous node. In this case, I'd report an
error.
Another problem would be if the node were the first node in the list. Then,
deleting it would invalidate the actual pointer to the head of the list.
(Which you say you don't have... but I'm assuming this is just for the sake
of this "puzzle", since any "real" program would certainly have to retain
the pointer to the head of the list!)
There is _no_way_, using a singly-linked list, and not having a pointer to
the head of that list, to "properly" delete the given node from that list.
You _can_ do like the example, making sure to check for NULL, of course, but
you'd need to throw an error in that case. And, you'd need to tell whoever
was supposedly using this method (your teacher? job interviewer?) that if
this _were_ by chance the head node, then any existing pointers to the head
node would no longer be valid.
By the way, when given questions in interviews (if that's the kind of
question this is), it's not always required that you come up with a perfect
solution. Sometimes, what the interviewer wants is to hear your analysis of
the problem. These kind of problems with the proposed solution are exactly
the kind of things you need to be able to consider for yourself when
designing real-world solutions. The more you're able to demonstrate your
analytical abilities, the more likely you'll get the job.
Of course, if this is just a puzzle posited by a friend or something, then
the answer is that it's simply not possible to do correctly in all cases.
Some, but not all.
-Howard