GATE / CS ARCHIVE

GATE CSE 2008 / QUESTION 62

Pairwise linked-list value swaps

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

GATE 2008, Q62 2 marks · MCQ
Report issue

Arrays & Linked Lists

Question 62, GATE 2008: The list initially contains 1,2,3,4,5,6,7. What does it contain after this C function?
struct node { int value; struct node *next; };
void rearrange(struct node *list) {
 struct node *p,*q; int temp;
 if (!list || !list->next) return;
 p=list; q=list->next;
 while(q) {
  temp=p->value; p->value=q->value; q->value=temp;
  p=q->next; q=p ? p->next : 0;
 }
}

(A) 1,2,3,4,5,6,7
(B) 2,1,4,3,6,5,7
(C) 1,3,2,5,4,7,6
(D) 2,3,4,5,6,7,1
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

1. p starts at the first node and q at the second. The temporary variable exchanges their value fields; no next pointer is modified.
2. p=q->next advances to the next pair’s first node, and q becomes its successor when it exists. Thus pairs (1,2), (3,4), (5,6) swap.
3. The final node 7 has no partner, so q becomes null and the loop stops. The sequence is 2,1,4,3,6,5,7, B.

Original paper, page 12