ProgrammingHardCompetitive coding (CP)

Starting at node 0, how many nodes does this linked walk visit before it reaches the sentinel -1? The next-index array is {3, 2, 0, -1}.

Starting at node 0, how many nodes does this linked walk visit before it reaches the sentinel -1? The next-index array is {3, 2, 0, -1}.
#include <stdio.h>
int main(void) {
    int nxt[] = {3, 2, 0, -1};
    int i = 0, cnt = 0;
    while (i != -1) {
        cnt++;
        i = nxt[i];
    }
    printf("%d", cnt);
}
  1. A. 3
  2. B. 2
  3. C. 4
  4. D. 1

Correct answer: B. 2

The walk goes from node 0 to node 3 and then reads -1 from node 3, so it visits 2 nodes counting the start; nodes 1 and 2 are never reached.

More C Programming questions

Exams that ask this topic