ProgrammingVery hardProduct company OA

What is printed?

What is printed?
struct N { int v; struct N *next; };
struct N n[5] = {{1, n + 1}, {2, n + 2}, {3, n + 3}, {4, n + 4}, {5, 0}};
struct N *h = n, *prev = 0;
for (int k = 0; k < 3 && h; k++) {
    struct N *t = h->next; h->next = prev; prev = h; h = t;
}
n[0].next = h;
for (struct N *p = prev; p; p = p->next) printf("%d", p->v);
  1. A. 321
  2. B. 32154
  3. C. 12345
  4. D. 32145

Correct answer: D. 32145

Three iterations of the standard reversal turn 1→2→3 into 3→2→1 with prev at node 3 and h left at node 4 (the untouched remainder). The old head, node 1, is now the tail of the reversed part, and n[0].next = h splices it to 4→5. Walking from prev prints 32145. Without that splice the list would end after 1 (output 321) and nodes 4, 5 would be unreachable – the usual bug in reverse-first-k.

More C Programming questions

Exams that ask this topic