Recursion

AP Computer Science A· difficulty 4/5

class Node { int v; Node n; Node(int v, Node n) { this.v = v; this.n = n; } }
public static int len(Node head) {
    if (head == null) return 0;
    return 1 + len(head.n);
}
Node h = new Node(1, new Node(2, new Node(3, null)));
System.out.println(len(h));

What is printed?

  • A

    3

    check_circle
  • B

    0

  • C

    2

  • D

    NullPointerException

Explanation

Recursion adds 1 per non-null node and stops at null. Length = 3.

Want 10 more like this — adaptive to your weak spots?

Related questions