GATE / CS ARCHIVE

GATE CSE 2022 / QUESTION 15

GATE CSE 2022 Q15

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

GATE 2022, Q15 1 mark · MCQ
Report issue

Arrays & Linked Lists

Question 15, GATE 2022: Reverse the links of an n-node singly linked list using O(1) auxiliary space, e.g. head→a→b→c→NULL becomes head→c→b→a→NULL. What is the best worst-case time? A Θ(n); B Θ(n log n); C Θ(n²); D impossible in O(1) space.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Keep previous, current and next pointers. Save current.next, reverse that link, and advance; at termination previous becomes the head. This uses constant auxiliary space and one pass, O(n). Reversing the links of an arbitrary n-node list requires Ω(n) link changes, so the optimum is Θ(n), A.

Executable pointer pseudocode:
prev=NULL; cur=head;
while(cur!=NULL){ next=cur.next; cur.next=prev; prev=cur; cur=next; }
head=prev;
Loop invariant: prev heads the already reversed prefix and cur heads the untouched suffix; saving next prevents losing the suffix. Only three pointer variables are needed, independent of n.

Original paper, page 13 · Answer key