The following C function takes a simply-linked list as input argument. It…
2010
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;
Attempted by 143 students.
Show answer & explanation
Correct answer: D
Key idea: detach the last node from the end, link it before the current head, and update head to point to it.
The loop leaves p pointing to the last node and q pointing to the node before last.
Set q->next = NULL to detach the last node from the tail.
Set p->next = head to link the detached node before the original head.
Set head = p to update the head pointer to the moved node.
Because the function already returns early for an empty list or a single-node list, these three statements correctly perform the move for lists with two or more nodes.
So the missing code is: q->next = NULL; p->next = head; head = p;
A video solution is available for this question — log in and enroll to watch it.