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- A. The loop never ends
- B. 4 → 3 → 2 → 1
- C. 1 → 2 → 3 → 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.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- A linked list has 3 nodes before the loop starts and a loop of 5 nodes. Floyd's slow pointer moves 1 step and fast pointer 2 steps per…
- ^ is exponentiation (highest precedence, right-associative). What is the postfix form of A + B C ^ D ^ E − F?
- What is the value of the postfix expression 2 3 2 ^ ^ (^ means power)?
- What is the minimum stack size needed to evaluate the postfix expression a b c d + e f − / + ?
- A queue is built from two stacks: enqueue pushes onto stack IN; dequeue pops from stack OUT, first moving everything from IN to OUT only…
- An array has only 0s, 1s and 2s. The Dutch National Flag algorithm sorts it in one pass. What are its time and extra space?