ProgrammingVery hard

Which code correctly removes node p from a doubly linked list, where p->prev and p->next may be NULL, and then frees it?

  1. A. free(p); if (p->prev) p->prev->next = p->next; if (p->next) p->next->prev = p->prev;
  2. B. if (p->prev) p->prev->next = p->next; free(p); if (p->next) p->next->prev = p->prev;
  3. C. p->prev->next = p->next; p->next->prev = p->prev; free(p);
  4. D. if (p->prev) p->prev->next = p->next; if (p->next) p->next->prev = p->prev; free(p);

Correct answer: D. if (p->prev) p->prev->next = p->next; if (p->next) p->next->prev = p->prev; free(p);

Links must be updated before the node is freed, and the NULL checks are needed at both ends. The other versions read freed memory or dereference NULL.

More C Programming questions

Exams that ask this topic