Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

GATE | GATE CS 2010 | Question 36

  • Difficulty Level : Easy
  • Last Updated : 28 Jun, 2021

The following C function takes a simply-linked list as input argument. It modifies the list by moving the last element to the front of the list and returns the modified list. Some part of the code is left blank.




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;
  }
  _______________________________
  return head;
}

Choose the correct alternative to replace the blank line.
(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;


Answer: (D)

Explanation: When the while loop ends, q contains address of second last node and p contains address of last node. So we need to do following things after while loop.
i) Set next of q as NULL (q->next = NULL).
ii) Set next of p as head (p->next = head).
iii) Make head as p ( head = p)
Step (ii) must be performed before step (iii). If we change head first, then we lose track of head node in the original linked list.
See https://www.geeksforgeeks.org/move-last-element-to-front-of-a-given-linked-list/ for more details.

Quiz of this Question

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!