The following C function takes a single-linked list of integers as a parameter…
2008
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 1, 2, 3, 4, 5, 6, 7 in the given order. What will be the contents of the list after the 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;
}
}
Answer: B. 2,1,4,3,6,5,7 — Concept: When two pointers identify adjacent nodes, swapping their value fields exchanges the stored integers without changing any next pointer or the…
- A.
1,2,3,4,5,6,7
- B.
2,1,4,3,6,5,7
- C.
1,3,2,5,4,7,6
- D.
2,3,4,5,6,7,1
Attempted by 257 students.
Show answer & explanation
Correct answer: B
Concept: When two pointers identify adjacent nodes, swapping their value fields exchanges the stored integers without changing any next pointer or the linked-list structure.
Advancing the first pointer to the node after the processed pair and deriving the second pointer from it makes each loop iteration handle the next disjoint pair; an unpaired final node is left untouched.
Application: Trace the values held by p and q at the start of each iteration.
Initially
prefers to the node holding 1 andqto the node holding 2. The three assignments throughtempexchange these values, giving 2, 1, 3, 4, 5, 6, 7.The updates
p = q->nextandq = p ? p->next : 0move the pair to the nodes holding 3 and 4. Their value swap gives 2, 1, 4, 3, 5, 6, 7.The same pointer updates select the nodes holding 5 and 6. Swapping their values gives 2, 1, 4, 3, 6, 5, 7.
After the next update,
prefers to the final node holding 7 andqbecomes 0. Thereforewhile(q)stops before another swap.
Cross-check: No next field is assigned anywhere, so node order cannot rotate; only the values in positions (1,2), (3,4), and (5,6) exchange places.
Result: The list contents are 2, 1, 4, 3, 6, 5, 7.
A video solution is available for this question — log in and enroll to watch it.
Explore the full course: Iocl Engineers Officers Grade A Paper 2