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?
- A. for (struct N *p = *head; p->next; p = p->next) ; p = node;
- B. for (struct N *p = *head; p; p = p->next) p = node;
- C. while (head->next) head = head->next; head->next = node;
- 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
- A queue with head and tail pointers is emptied by dequeuing its only node. What must the dequeue do to keep the queue correct?
- A recursive function removes all nodes equal to x from a singly linked list and returns the new head. Which return statement is the right…
- A program creates an array of 10^6 pointers and then one malloc block per pointer, with 10^6 frees at the end. What is the total number of…
- What is the effect of realloc(p, 0) when p came from malloc, in the C standard's terms?
- A function returns a pointer to a dynamically allocated copy of its argument string. Which signature is the most correct for the caller's…
- int m = malloc(3 sizeof m); for (int i = 0; i < 3; i++) m[i] = malloc(4 sizeof m); What is the number of allocation calls made in total?