5. You want to implement a queue using a linked list that supports enqueue and dequeue in O(1) time. Which of the following changes is necessary to the enqueue method to handle the edge case when the queue is empty?
hard
A. Set both head and tail to the new node when queue is empty
B. Set only tail to the new node when queue is empty
C. Set new node's next to head when queue is empty
D. Set tail.next to head when queue is empty
Solution
Step 1: Understand queue empty state
When queue is empty, both head and tail pointers are None.
Step 2: Enqueue first element must update both pointers
To maintain O(1) enqueue and dequeue, head and tail must both point to the new node.
Step 3: This ensures correct linking and prevents errors
Without setting both, dequeue or next enqueue operations may fail or cause errors.
Final Answer:
Set both head and tail to the new node when queue is empty -> Option A
Quick Check:
Empty queue enqueue sets head and tail [OK]
Hint: Empty queue needs head and tail set to new node [OK]
Common Mistakes:
Setting only tail or only head on empty enqueue
Linking new node incorrectly to head or tail
Not handling empty queue edge case
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.