B. Deleting temp before moving head causes runtime error.
C. The function does not update the original head pointer outside the function.
D. No error; code works correctly.
Solution
Step 1: Understand pointer passing in C++
Function receives head by value, so changes inside do not affect original head.
Step 2: Identify missing update to original head
Updating local head pointer does not update the caller's head, so list head remains unchanged.
Final Answer:
The function does not update the original head pointer outside the function. -> Option C
Quick Check:
Pointer passed by value, original head unchanged [OK]
Hint: Pass head by reference to update original pointer [OK]
Common Mistakes:
Assuming head changes outside function
Deleting node before moving head
Confusing pointer and value passing
Ignoring nullptr checks
5. Given a singly linked list, write the correct approach to delete the first node safely and update the head pointer in C++. Which of the following code snippets correctly achieves this?
hard
A. void deleteFirstNode(Node* head) {
Node* temp = head;
head = head->next;
delete temp;
}
B. void deleteFirstNode(Node*& head) {
if (head == nullptr) return;
Node* temp = head;
head = head->next;
delete temp;
}