7.
Texas Instruments technical mcq question, verified with a worked answer. Free to practise - no sign-up.
Understanding circular linked lists**
scan(*to, &item);
ptr → data = item;
if(head == NULL)
{
head = ptr;
ptr → next = head;
}
else
{
temp = head;
while(temp → next != head)
{
temp = temp → next;
ptr → next = head;
temp → next = ptr;
head = ptr;
}
}
Note: head here represents the first node of the linked list.
Show answer & explanation
The provided code contains a critical logical error within the 'else' block: the pointer updates (ptr->next = head, temp->next = ptr, head = ptr) are placed inside the while loop. This causes the list to be corrupted during the first iteration, failing to correctly implement either a 'beginning' or 'end' insertion.
Step-by-step Derivation:
Step 1: Analyze the 'if(head == NULL)' block. This correctly handles the first node by setting head to ptr and making it point to itself (circular). This part is correct for both beginning and end insertion.
Step 2: Analyze the 'else' block. The code enters a while loop: 'while(temp -> next != head)'.
Step 3: Examine the loop body. Inside the loop, it executes:
a) ptr -> next = head;
b) temp -> next = ptr;
c) head = ptr;
Step 4: Trace the execution. In the very first iteration of the loop, 'head' is updated to 'ptr'. Because 'head' has changed, the loop condition 'temp -> next != head' is evaluated against the new head. More importantly, by updating 'head = ptr' inside the loop, the original reference to the start of the list is lost immediately.
Step 5: Compare with standard algorithms.
- For insertion at the beginning: The loop should find the last node, then the last node's next should point to the new node, and the new node's next should point to the old head, then head is updated. The updates must happen AFTER the loop.
- For insertion at the end: The loop should find the last node, then the last node's next should point to the new node, and the new node's next should point to head. The head should NOT be updated.
Step 6: Conclusion. Because the pointer manipulations and the head update are inside the loop, the code logic is broken and does not perform a valid insertion at either the beginning or the end.