GATE / CS ARCHIVE

GATE CSE 2010 / QUESTION 36

Moving the last linked-list node first

Programming in C · Pointers & Memory · Full GATE CSE 2010 paper

GATE 2010, Q36 2 marks · MCQ
Report issue

Pointers & Memory

Question 36, GATE 2010: Complete this C function so it moves the last node of a singly linked list to the front and returns the new head.
typedef struct node { int value; struct node *next; } Node;
Node *move_to_front(Node *head) {
 Node *p,*q;
 if(head==NULL || head->next==NULL) return head;
 q=NULL; p=head;
 while(p->next!=NULL) { q=p; p=p->next; }
 /* BLANK */
 return head;
}
Options: (A) q=NULL; p->next=head; head=p;; (B) q->next=NULL; head=p; p->next=head;; (C) head=p; p->next=q; q->next=NULL;; (D) q->next=NULL; p->next=head; head=p;.
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

At loop exit p points to the last node and q to its predecessor. First set q->next=NULL to detach p, then p->next=head to link p before the old first node, and finally head=p. This is option D. Updating head before p->next would lose the old head and can create a self-loop; the early return already handles lists shorter than two nodes.

For A→B→C, the loop ends with p=C and q=B. Detach B→C, point C→A and set head=C, obtaining C→A→B→NULL. Choice A only clears the local variable q and leaves B linked to C, producing a cycle. Choice B makes C point to itself. Choice C loses the old head connection by linking the last node to its predecessor instead.

Original paper, page 9