edited by
7,956 views
24 votes
24 votes

The following C function takes a singly-linked list of integers as a parameter and rearranges the elements of the list. The list is represented as pointer to a structure. 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;
      }
}
  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

2 Answers

Best answer
28 votes
28 votes

It is (B) $2, 1, 4, 3, 6, 5, 7$:

As, $p$ and $q$ are swapping each other where $q$ is $p \rightarrow next $ all the time. 

edited by
11 votes
11 votes
struct node {int value; struct node *next;);
void rearrange (struct node *list) {
    struct node *p, *q;
    int temp;
    if (!list || !list -> next) return; // just check 1st time two adjacent node are there or not. if not program is finish . for example take one node or 0 node in linked list output will be same as input.
    p = list; q = list -> next; two pointer to point two adjacent node p point first node  q point second node which is adjacent to first.
    while (q) this will check always two adjacent present or not like if at one point only p point some node and q point to null then loop stop running.
      { 
        1.temp = p -> value;
        2.p -> value = q -> value;
        3.q -> value = temp; till here swapping done via temp variable.
        4.p = q -> next; just point next node
        5.q = p ? p -> next : 0; this will one if p point to some node then q point to its next node. if p point to null then q also point 0.
      }
}

Finally while loop take care two node present to swap .

if one node present at any time between running of program then while loop terminate.

Answer:

Related questions

27 votes
27 votes
4 answers
1
64 votes
64 votes
7 answers
2
Ishrat Jahan asked Nov 3, 2014
22,755 views
In a binary tree, for every node the difference between the number of nodes in the left and right subtrees is at most $2$. If the height of the tree is $h 0$, then the m...
67 votes
67 votes
2 answers
3
53 votes
53 votes
7 answers
4
Ishrat Jahan asked Nov 3, 2014
13,470 views
The numbers $1, 2, .\dots n$ are inserted in a binary search tree in some order. In the resulting tree, the right subtree of the root contains $p$ nodes. The first number...