ProgrammingVery hard

A tail-insertion function takes a pointer to the head pointer, so it can work on an empty list. Which loop finds the link to change?

  1. A. for (struct N *p = *head; p->next; p = p->next) ; p = node;
  2. B. for (struct N *p = *head; p; p = p->next) p = node;
  3. C. while (head->next) head = head->next; head->next = node;
  4. D. for (struct N **pp = head; *pp; pp = &(*pp)->next) ; then *pp = node;

Correct answer: D. for (struct N **pp = head; *pp; pp = &(*pp)->next) ; then *pp = node;

pp walks the links and stops at the NULL link, which is the one to replace. The other versions dereference an empty list, or assign to a local copy that does not change the list.

More C Programming questions

Exams that ask this topic