The following C function takes a single-linked list of integers as a parameter and rearranges the elements of the list. The function is called with the list containing the integers in the given order. What will be the contents of the list after function completes execution?
struct node {
int value;
struct node *next;
};
void rearrange(struct node *list) {
struct node *p, *q;
int temp;
if (!list || !list -> next) return;
p = list; q = list -> next;
while(q) {
temp = p -> value; p->value = q -> value;
q->value = temp; p = q ->next;
q = p? p ->next : 0;
}
}
View worked solution
Answer: B
To find the contents of the list after the execution of the rearrange function, let us trace the execution step-by-step.
The initial list is:
Before entering the loop, the pointers are initialized as:
p = list(points to the node with value )q = list->next(points to the node with value )
Step-by-Step Execution:
-
First Iteration (
qis not NULL):- Swap the values of
pandq: The values and are swapped. - The list becomes:
- Update pointers:
p = q->next(points to the node with value )q = p ? p->next : 0(points to the node with value )
- Swap the values of
-
Second Iteration (
qis not NULL):- Swap the values of
pandq: The values and are swapped. - The list becomes:
- Update pointers:
p = q->next(points to the node with value )q = p ? p->next : 0(points to the node with value )
- Swap the values of
-
Third Iteration (
qis not NULL):- Swap the values of
pandq: The values and are swapped. - The list becomes:
- Update pointers:
p = q->next(points to the node with value )q = p ? p->next : 0(sincep->nextisNULL,qbecomesNULL)
- Swap the values of
At the next check, the loop condition while(q) fails because q is NULL. The function terminates.
The final contents of the list are:
Therefore, the correct option is B.
Free practice · Your answers on this page are not saved.
