Data Structures & AlgorithmsHardProduct-company MCQ pattern

What does this function print for the list 1 → 2 → 3 → 4 → 5 → 6?

What does this function print for the list 1 → 2 → 3 → 4 → 5 → 6?
def f(node):
    if node is None:
        return
    if node.next:
        f(node.next.next)
    print(node.val, end=" ")

f(head)
  1. A. 5 3 1
  2. B. 2 4 6
  3. C. 6 4 2
  4. D. 1 3 5

Correct answer: A. 5 3 1

f(1) calls f(3), which calls f(5); 5.next is 6 and 6.next is None, so f(None) returns. Printing happens after the call, as the recursion unwinds: 5, then 3, then 1. Printing before the call would give 1 3 5.

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

Exams that ask this topic