Predict the output
What does this print?
from dataclasses import dataclass
@dataclass(eq=False)
class Link:
val: int
next: "Link | None" = None
head = Link(1, Link(2, Link(3)))
head.next = head.next.next if head.next else None
vals = []
cur: Link | None = head
while cur:
vals.append(cur.val)
cur = cur.next
print(vals)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A [1, 3]
Right: the arrow from 1 now skips over 2.
Removing a link from a chain is one arrow change; nothing is shifted, which is the main contrast with an array.
Why not the others?
- B [1, 2, 3]. The second link is bypassed by the reassignment.
- C [2, 3]. The head itself is still the link holding 1.