GATE Computer ScienceVery hardGATE CS (PYQ pattern)

Two singly linked lists merge into a common tail: list X has 7 nodes before the merge point, list Y has 11 nodes before it, and the shared tail has 5 nodes. Pointers p = headX and q = headY advance one node per step; when a pointer is at the last node of its list its next move goes directly to the head of the other list (there is no NULL step), and the process stops when p == q. After how many steps (0 steps = the initial comparison) does the loop stop, and at which shared-tail node (1 = merge point)?

  1. A. 22 steps, shared node 1
  2. B. 23 steps, shared node 1
  3. C. 23 steps, shared node 2
  4. D. 27 steps, shared node 1

Correct answer: B. 23 steps, shared node 1

p walks list X (12 nodes), then the 11 unique nodes of Y; q walks list Y (16 nodes), then the 7 unique nodes of X. Both have taken 12 + 11 = 16 + 7 = 23 steps when they stand on the merge point.

More Programming and Data Structures (GATE) questions

Exams that ask this topic