The following C function takes a singly-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.
View worked solution
Answer: D
To move the last node of a singly-linked list to the front, we first need to identify the last node and the second-to-last node. Let's trace the state of the pointers after the while loop terminates:
- The loop condition is
p->next != NULL. When the loop terminates,ppoints to the last node of the list. - Since
qtracks the node just behindp(viaq = p),qpoints to the second-to-last node of the list.
To move the last node (p) to the front of the list, we must perform the following three logical steps in order:
- Disconnect the last node: The second-to-last node
qmust now become the new end of the list, so itsnextpointer must be set toNULL:q->next = NULL; - Link the last node to the old head: The node
p(which is being moved to the front) must point to the current first node of the list (head):p->next = head; - Update the head pointer: The
headpointer must now point to the new first nodep:head = p;
Combining these steps, the correct sequence of statements is:
This matches Option D.
Why other options are incorrect:
- Option A: Setting
q = NULLloses the reference to the second-to-last node, leaving itsnextpointer still pointing top, which creates a cycle. - Option B: Executing
head = p;beforep->next = head;makesp->nextpoint topitself, creating a self-loop. - Option C: Setting
p->next = q;points the new head back to the second-to-last node, which incorrectly reverses the end of the list and loses the rest of the list.
Free practice · Your answers on this page are not saved.
