Data Structures & AlgorithmsHardProduct-company MCQ pattern

This code tries to reverse the singly linked list 1 → 2 → 3 → 4, but its last line has been changed from cur = nxt. What does the list starting at head contain afterwards?

This code tries to reverse the singly linked list 1 → 2 → 3 → 4, but its last line has been changed from cur = nxt. What does the list starting at head contain afterwards?
prev, cur = None, head
while cur:
    nxt = cur.next
    cur.next = prev
    prev = cur
    cur = cur.next
head = prev
  1. A. The loop never ends
  2. B. 4 → 3 → 2 → 1
  3. C. 1 → 2 → 3 → 4
  4. D. Only 1

Correct answer: D. Only 1

By the time cur = cur.next runs, cur.next has already been set to prev (None), so the loop stops after one pass. head becomes node 1 with next = None, and nodes 2–4 are lost.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic