GATE / CS ARCHIVE

GATE CSE 1998 / QUESTION 19(a)

Linked-list pointer manipulation

Data Structures · Arrays & Linked Lists · Full GATE CSE 1998 paper

GATE 1998, Q19(a) Descriptive
Report issue

Arrays & Linked Lists

Question 19(a), GATE 1998: Initially p points to node i in i→i+1→i+2→i+3→suffix. Execute q=p.next; p.next=q.next; q.next=(q.next).next; (p.next).next=q. GateForum instead prints p.next, not q.next, on the third line. Explain both.
Question 19(a), GATE 1998: Initially p points to node i in i→i+1→i+2→i+3→suffix. Execute q=p.next; p.next=q.next; q.next=(q.next).next; (p.next).next=q. GateForum instead prints p.next, not q.next, on the third line. Explain both.
Tap to enlarge
Answer & solution

Answer: It swaps nodes i+1 and i+2 (no official key was published)

Write P=i, A=i+1, B=i+2 and C=i+3. Initially P→A→B→C→suffix. Third line, step 1 sets q=A. Step 2 bypasses A by setting P.next=B. Step 3 sets A.next=C, preserving the link to the suffix. Step 4 sets B.next=A. The resulting chain is P→B→A→C→suffix: the two adjacent nodes after p have been exchanged without copying their payloads. This requires those nodes and the next fields used in the expressions to exist.

After the first two steps, q=A, P.next=B, A.next=B and B.next=C. Its third line sets P.next=C instead of changing A.next. Its last line then sets C.next=A. Thus from P the chain becomes P→C→A→B→C→..., a three-node cycle; the original suffix after C is detached from this chain. It is not an adjacent swap.

The correct algorithmic explanation cannot establish which version appeared in the official original.

Original paper, page 7