GATE | GATE CS 2010 | Question 36
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
Recommended Posts:
- GATE | GATE CS 2010 | Question 65
- GATE | GATE CS 2010 | Question 65
- GATE | GATE CS 2010 | Question 24
- GATE | GATE CS 2010 | Question 23
- GATE | GATE CS 2010 | Question 22
- GATE | GATE CS 2010 | Question 21
- GATE | GATE CS 2010 | Question 20
- GATE | GATE CS 2010 | Question 19
- GATE | GATE CS 2010 | Question 18
- GATE | GATE CS 2010 | Question 65
- GATE | GATE CS 2010 | Question 16
- GATE | GATE CS 2010 | Question 15
- GATE | GATE CS 2010 | Question 26
- GATE | GATE CS 2010 | Question 27
- GATE | GATE CS 2010 | Question 37



