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,7Concept: When two pointers identify adjacent nodes, swapping their value fields exchanges the stored integers without changing any next pointer or the…

  1. A.

    1,2,3,4,5,6,7

  2. B.

    2,1,4,3,6,5,7

  3. C.

    1,3,2,5,4,7,6

  4. 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.

  1. Initially p refers to the node holding 1 and q to the node holding 2. The three assignments through temp exchange these values, giving 2, 1, 3, 4, 5, 6, 7.

  2. The updates p = q->next and q = p ? p->next : 0 move the pair to the nodes holding 3 and 4. Their value swap gives 2, 1, 4, 3, 5, 6, 7.

  3. The same pointer updates select the nodes holding 5 and 6. Swapping their values gives 2, 1, 4, 3, 6, 5, 7.

  4. After the next update, p refers to the final node holding 7 and q becomes 0. Therefore while(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

Loading lesson…