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?
- A. free(p); if (p->prev) p->prev->next = p->next; if (p->next) p->next->prev = p->prev;
- B. if (p->prev) p->prev->next = p->next; free(p); if (p->next) p->next->prev = p->prev;
- C. p->prev->next = p->next; p->next->prev = p->prev; free(p);
- 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
- Merging two sorted singly linked lists of length 3 each with the standard merge, what is the largest number of key comparisons needed?
- With a 4-byte int and an 8-byte pointer, natural alignment, what is sizeof(struct N) for struct N { int v; struct N next; };?
- A linked list is built by appending n nodes one by one, each time walking from the head to the last node. About how many node visits does…
- A stack is implemented with a singly linked list, pushing at the head. The operations are push 1, push 2, pop, push 3, push 4, pop, pop…
- A queue is kept as a singly linked list with head and tail pointers. Enqueue 1, 2, 3, dequeue twice, enqueue 4, then dequeue once. Which…
- Which loop correctly frees every node of a singly linked list whose head is p?