C. for(int i=0; i<10; i++) { if(slow == fast) return true; slow = slow->next; fast = fast->next; } return false;
D. if(head == nullptr) return true; else return false;
Solution
Step 1: Understand slow and fast pointer method
Two pointers move at different speeds; if they meet, a loop exists.
Step 2: Analyze code correctness
while(fast != nullptr && fast->next != nullptr) { slow = slow->next; fast = fast->next->next; if(slow == fast) return true; } return false; correctly moves slow by one and fast by two nodes, checking for equality inside the loop.
A. The loop condition should check fast->next != nullptr to avoid null pointer dereference
B. The slow pointer should move two steps instead of one
C. The function should return false inside the loop
D. The function should initialize slow and fast to nullptr
Solution
Step 1: Check loop condition safety
fast->next->next is accessed, so fast->next must not be nullptr to avoid crash.
Step 2: Correct loop condition
Change while(fast != nullptr) to while(fast != nullptr && fast->next != nullptr) to prevent null pointer dereference.
Final Answer:
The loop condition should check fast->next != nullptr to avoid null pointer dereference -> Option A
Quick Check:
Check fast and fast->next to avoid crash [OK]
Hint: Always check fast->next before fast->next->next [OK]
Common Mistakes:
Not checking fast->next leads to runtime error
Moving slow pointer incorrectly
Returning false too early
5. You have a singly linked list where the last node might point back to any node, making it circular. How would you modify the list to remove the circular link and make it linear again?
hard
A. Set head to nullptr to clear the list
B. Delete all nodes after the head node
C. Reverse the linked list to break the loop
D. Detect the loop using slow and fast pointers, then find the node before the loop start and set its next to nullptr
Solution
Step 1: Detect loop using slow and fast pointers
Use two pointers moving at different speeds; if they meet, a loop exists.
Step 2: Find the node before loop start and break the loop
Reset one pointer to head, move both one step until they meet; the node before meeting point is loop end. Set its next to nullptr.
Final Answer:
Detect the loop using slow and fast pointers, then find the node before the loop start and set its next to nullptr -> Option D
Quick Check:
Find loop start, break link to remove circular [OK]
Hint: Find loop start, set previous node's next to nullptr [OK]
Common Mistakes:
Deleting nodes unnecessarily
Reversing list does not remove loop
Setting head to nullptr loses entire list
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.