ProgrammingVery hardProduct company OA

What is printed?

What is printed?
struct N { int v; struct N *nx; };
struct N c = {3, NULL}, b = {2, &c}, a = {1, &b};
struct N *prev = NULL, *cur = &a, *nx;
while (cur) {
    nx = cur->nx;
    cur->nx = prev;
    prev = cur;
    cur = nx;
}
printf("%d %d %d", prev->v, prev->nx->v, a.nx == NULL);
  1. A. 3 2 1
  2. B. 3 1 1
  3. C. 1 2 0
  4. D. 3 2 0

Correct answer: A. 3 2 1

This is the standard in-place reversal: each node's link is turned to point backwards. Afterwards prev is the old tail c (3), c now links to b (2), and the old head a has become the tail, so a.nx is NULL (1).

More C Programming questions

Exams that ask this topic