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?
- A. 1 3 2 6 5 4 10 9 8 7 11 12
- B. 1 3 2 6 5 4 10 9 8 7 12 11
- C. 2 1 5 4 3 9 8 7 6 12 11 10
- 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.
Practise more Programming and Data Structures (GATE) questionsProgramming and Data Structures (GATE): notes and key points
More Programming and Data Structures (GATE) questions
- Keys 5, 3, 8, 3, 9, 1, 8, 5 are inserted one by one into an initially empty sorted singly linked list; each insertion scans from the head…
- Two sorted lists, X with 5 keys and Y with 7 keys (all 12 keys distinct), are merged with the standard two-pointer merge that stops…
- A singly linked list 10 -> 11 -> ... -> 19 is rearranged by a routine that places all nodes at odd positions (1st, 3rd, ...) first…
- A circular singly linked list holds nodes 1 to 100 in order. Deletion starts with node 1 itself and then removes every second remaining…
- struct T { int k; struct T l, r; }; int f(struct T n) { return n ? 1 + max(f(n->l), f(n->r)) : 0; } int g(struct T n) { return n ?…
- Keys 30, 10, 40, 5, 20, 35, 50, 15, 25, 45 are inserted in this order into an empty BST, and then the left and right pointers of every…