• edited by
27,741 views
57 57 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$

7 Answers

Best answer
50 50 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
2 2 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:
Position:
Show:

Related questions

74 74 votes
4 answers 4 answers
36.1k
36.1k views
Kathleen asked Sep 12, 2014
36,071 views
Which of the following are NOT true in a pipelined processor?Bypassing can handle all RAW hazardsRegister renaming can eliminate all register carried WAR hazardsControl h...
195 195 votes
7 answers 7 answers
61.8k
61.8k views
Kathleen asked Sep 12, 2014
61,788 views
You are given the postorder traversal, $P$, of a binary search tree on the $n$ elements $1, 2, \dots, n$. You have to determine the unique binary search tree that has $P...
44 44 votes
3 answers 3 answers
21.4k
21.4k views
Arjun asked Nov 27, 2016
21,412 views
Consider the following $\text{ER}$ diagramThe minimum number of tables needed to represent $M$, $N$, $P$, $R1$, $R2$ is Which of the following is a correct attribute set ...
30 30 votes
3 answers 3 answers
11.9k
11.9k views
go_editor asked Apr 23, 2016
11,873 views
Consider the following C program that attempts to locate an element $x$ in an array $Y[ \ ]$ using binary search. The program is erroneous. f (int Y[10] , int x) { int i,...