2
$\begingroup$

Regarding: delete a node from a linked list algorithm,in procedural languages with garbage-collection. Should there be a step in the algorithm, of setting the removed-node-next-pointer to null ?

(Several high-school-CS-teachers in my area teach YES, while others teach NO)

What is the right approach?

/thanks ran

$\endgroup$
  • $\begingroup$ The next pointer of the node that was deleted does not have to be reset. I was wondering whether it would help - from the standpoint of freeing up memory - to set this pointer to null. But a garbage collection routine would find this deleted node to be unreachable regardless of the value of its next pointer. So it's not necessary to set this pointer to null. $\endgroup$ – Ashwin Ganesan Nov 27 at 10:29
1
$\begingroup$

If you mean the next pointer of the node that was deleted, as far as I know it is normally not necessary to set the pointer to null. Once the node is deleted, if the code is not buggy, then the code should not access the node after it is deleted, so the value of its next pointer should be irrelevant. Sometimes some people do set the pointer to null, as a form of defensive programming (just in case the program is buggy and accesses that node after it was deleted).

I suggest that a useful exercise would be to ask your teachers why they teach yes or no. Hearing their reasoning might be instructive and interesting!

$\endgroup$
  • $\begingroup$ +1 for asking why. The teachers are there to learn from, after all. $\endgroup$ – Ben I. Nov 23 at 1:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.