ProgrammingVery hardTCS NQT · Infosys

What is printed?

What is printed?
#include <stdio.h>
struct N { int v; struct N *nx; };
struct N *rev(struct N *h, struct N *prev) {
    if (!h) return prev;
    struct N *nx = h->nx;
    h->nx = prev;
    return rev(nx, h);
}
int main(void) {
    struct N c = {3, 0}, b = {2, &c}, a = {1, &b};
    struct N *h = rev(&a, 0);
    for (; h; h = h->nx) printf("%d ", h->v);
}
  1. A. 1 2 3
  2. B. 2 3 1
  3. C. 3 2 1
  4. D. 3 1 2

Correct answer: C. 3 2 1

The recursion reverses the links one node at a time and returns the old tail as the new head, so the list prints 3, 2, 1.

More C Programming questions

Exams that ask this topic