The GATE Grind

GATE 2010 CS (CS1) – Question 46

Programming and Data Structures · Linked Lists · 2 marks · Multiple choice

For a singly linked list with at least two nodes, fill the blank to move its last node to the front.

Node *move(Node *head) {
  Node *p=head, *q=NULL;
  while (p->next != NULL) { q=p; p=p->next; }
  /* blank */
  return head;
}
  1. q=NULL; p->next=head; head=p;
  2. q->next=NULL; head=p; p->next=head;
  3. head=p; p->next=q; q->next=NULL;
  4. q->next=NULL; p->next=head; head=p;

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: (D) q->next=NULL; p->next=head; head=p;

Explanation

At loop exit p points to the last node and q to its predecessor. First terminate the shortened list with q->next=NULL. Link the old last node to the old head using p->next=head, then update head=p. This is D; changing head before linking would lose the original front or create a self-loop.

More Linked Lists questions

All Linked Lists questions →