GATE / CS ARCHIVE

GATE CSE 1997 / QUESTION 8

Swap consecutive linked-list nodes

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

GATE 1997, Q8 5 marks · Descriptive
Report issue

Arrays & Linked Lists

Question 8, GATE 1997: A singly linked list L=(a1,…,an), n≥0, has nodes with fields next:^list and val:integer. Swap adjacent pairs a_(2i−1),a_(2i), 1≤i≤floor(n/2), by filling the four boxes:
1 function change(p:^list):^list;
2 var q,t:^list;
3 begin
4   if p=nil then change:=p
5   else if p^.next=nil then change:=[B5]
6   else begin
7     q:=p^.next;
8     [B8]:=q;
9     t:=q^.next;
10    [B10]:=p;
11    [B11]:=change(t)
12  end
13 end
Tap to enlarge
Answer & solution

Answer: B5=p; B8=change; B10=q^.next; B11=p^.next. (no official key was published)

The required fillings are line 5: p; line 8: change; line 10: q^.next; line 11: p^.next. With them, the nontrivial branch is

q := p^.next;
change := q;
t := q^.next;
q^.next := p;
p^.next := change(t).

Before the change, the first two nodes and the remaining list have the shape p → q → t. The function must return q as the new head, so line 8 assigns the function result rather than overwriting a next pointer. Save t before reversing q's link; otherwise the remaining list could be lost. Then q^.next:=p reverses the first pair, and p^.next:=change(t) joins its second node to the recursively transformed remainder. The final shape is q → p → change(t).

For an empty list, returning nil preserves it. For a one-node list, returning p preserves the last unpaired node. These are also the induction bases. Assuming the recursive call correctly swaps all pairs in the suffix of length n−2, linking the reversed first pair to that result swaps every required pair in the whole list and preserves every node exactly once.

For example, 1→2→3→4→5 becomes 2→1→4→3→5. The code exchanges nodes through pointers, not merely their stored integer values. It takes Θ(n) time and Θ(n) recursive-stack space, with about floor(n/2) pair-processing calls. Pascal's function-name assignment in line 8 is the mechanism for returning a pointer; it is not another recursive call.

Original paper, page 6