GATE Computer ScienceHardGATE CS (PYQ pattern)

struct node { int d; struct node *n; }; struct node *f(struct node *p, int k) { if (p == NULL) return NULL; struct node *cur = p, *prev = NULL, *nx; int c = 0; while (cur != NULL && c < k) { nx = cur->n; cur->n = prev; prev = cur; cur = nx; c++; } p->n = f(cur, k + 1); return prev; } The list 1 -> 2 -> ... -> 12 is passed as f(head, 1). What is the returned list?

  1. A. 1 3 2 6 5 4 10 9 8 7 11 12
  2. B. 1 3 2 6 5 4 10 9 8 7 12 11
  3. C. 2 1 5 4 3 9 8 7 6 12 11 10
  4. D. 1 4 3 2 8 7 6 5 12 11 10 9

Correct answer: B. 1 3 2 6 5 4 10 9 8 7 12 11

Each call reverses the next k nodes (or all that remain, if fewer) and hands the rest to a call with k + 1; the old first node p, now the group's tail, is linked to that result. Groups: {1}, {2, 3}, {4, 5, 6}, {7, 8, 9, 10}, {11, 12} (only 2 left for k = 5, and the loop still reverses them). Result: 1 3 2 6 5 4 10 9 8 7 12 11.

More Programming and Data Structures (GATE) questions

Exams that ask this topic