ProgrammingHardCognizant GenC · TCS NQT

What is printed?

What is printed?
class N:
    def __init__(self, v, nxt=None):
        self.v, self.nxt = v, nxt
def rev(h):
    prev = None
    while h:
        h.nxt, prev, h = prev, h, h.nxt
    return prev
h = N(1, N(2, N(3)))
r = rev(h)
out = []
while r:
    out.append(r.v)
    r = r.nxt
print(out)
  1. A. [3, 2, 1]
  2. B. [1, 2, 3]
  3. C. [2, 3, 1]
  4. D. [3]

Correct answer: A. [3, 2, 1]

The tuple assignment evaluates its right side first, so each node's next pointer is redirected before the walk moves on. The list comes out reversed as 3, 2, 1.

More Python Programming questions

Exams that ask this topic