Curated · Linked Lists

MSQ · 2 marks · Problem PROG-DSTR-0357

Each node of a singly linked list has fields v and next. The function below reverses the list whose head is h, and returns the new head.
def rev(h):
    p = None
    while h:
        STATEMENT
    return p
Python evaluates the whole right-hand side of a multiple assignment first and then assigns the targets from left to right. Which of the following, used as STATEMENT, make rev correct for every list?
  1. A
    h.next, p, h = p, h, h.next
  2. B
    p, h.next, h = h, p, h.next
  3. C
    h, h.next, p = h.next, p, h
  4. D
    nxt = h.next; h.next = p; p = h; h = nxt

Solve it on GATE DA practice →More Basic Data Structures problems

Show the worked solution\[\boxed{\text{the right side is evaluated first; a target such as h.next is evaluated when it is assigned}}\]The right side is evaluated with the old values of h and p. What matters is whether h has already changed when the target h.next is assigned.(A) h.next is assigned while h is still the old node, then p and h move on — correct.(B) p is assigned first, but h is unchanged, so h.next \(=\) old p is still set on the right node — correct.(C) h moves to the next node first, so the new h gets next \(=\) old p, and the old node is never relinked; on the list 1, 2, 3 the second iteration sets h to None and then assigns to None.next, which raises an error — incorrect.(D) The usual version with a temporary variable — correct.Answer: A, B, D

GATE DA practice: past exam problems by chapter, with worked solutions · gatedaprep.com