ProgrammingVery hard
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 one for the recursive call?
- A. return n->next; always, whether or not n->v equals x
- B. n->next = remove_all(n->next, x); return n; (after freeing n when n->v == x, returning n->next)
- C. n->next = NULL; return n;
- D. return remove_all(n, x); to restart from the same node
Correct answer: B. n->next = remove_all(n->next, x); return n; (after freeing n when n->v == x, returning n->next)
When the node matches, the result is the rest of the list. Otherwise the node stays and its next link is updated. The other forms drop nodes that should remain or loop forever.
More C Programming questions
- 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?
- A doubly linked list node has prev and next. What must happen before freeing the node p in the middle of the list?
- A linked stack stores nodes with a pointer to the top. Push and pop run in O(1). What is the cost of freeing the whole stack when it has n…