edited by
19,031 views
42 votes
42 votes

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 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;
    }   
}
  1. $1, 2 ,3, 4, 5, 6, 7$
  2. $2, 1, 4 ,3, 6, 5, 7$
  3. $1, 3, 2, 5, 4, 7, 6$
  4. $2, 3, 4, 5, 6, 7, 1$
edited by

4 Answers

Best answer
35 votes
35 votes

The loop is interchanging the adjacent elements of the list. But after each interchange, next interchange starts from the unchanged elements only (due to $p = q \rightarrow  next$;).

$1^{st}$ iteration: $1, 2, 3, 4, 5, 6, 7$
            $\Rightarrow  2, 1, 3, 4, 5, 6, 7$

$2^{nd}$ iteration: $2, 1, 4, 3, 5, 6, 7$

$3^{rd}$ iteration: $2, 1, 4, 3, 6, 5, 7$

$p$ pointing to $7$ and $q$ is pointing to $\textsf{NULL} (0)$, as $p$ is false hence $q=p?$ $p  \rightarrow \textsf{next}$:$0$; will return  $q=0$ ending the loop. (In C language NULL is having the value 0).

Answer is option B.

edited by
1 votes
1 votes
original-1,2,3,4,5,6,7

1st iteration-2,1,3,4,5,6,7

2nd iteration- 2,1,4,3,5,6,7

3rd iteration- 2,1,4,3,6,5,7

after this step p pointing to 7  and q pointing to NULL.

at last ternary operator execute -  q = p->next (as p hold address of 7)  i.e q= NULL

while loop terminate as q=NULL
so answer is B
Answer:

Related questions