-
The following C function takes a simply-linked list as input argument. It modifies the 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.
type def 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.
-
- q = NULL; p - > next = head; head = p;
- q - > next = NULL; head = p; p - > next = head;
- head = p; p -> next = q; q -> next = NULL;
- q-> next = NULL; p-> next = head; head = p;
- q = NULL; p - > next = head; head = p;
Correct Option: D
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.