What will be the contents of the list after function completes execution?

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.     

 

 if (!list || !list -> next) return;what does this line mean?

  also this line  q = p? p ->next : 0

8Comments
Sumit Verma @sumitverma 1 Jun 2017 12:41 pm

The correct answer will be 2, 1, 4, 3, 6, 5, 7.
 if (!list || !list -> next) return // This line will check if the list is NULL, or having only one element. 
q = p? p-> next : 0 // This line will assign the value of q. if p is not null, then next of it will be assigned to q otherwise the value of q will be 0. If we will not write this line, we may get a segmentation fault.

shweta @shweta1920 1 Jun 2017 01:26 pm

why if(!list) .. it should written if list !=null

Sumit Verma @sumitverma 1 Jun 2017 01:54 pm

if(!list) is equal to if (list = = Null).

Virtual GATE @virtualgate 2 Jun 2017 02:49 pm

it is better and safer to use (!list) than (list==NULL) as while implementation there might be some memory - segmentation fault errors.

shweta @shweta1920 11 Jun 2017 07:32 pm

@virtualgate ... means?...I mean plz elaborate ur answer ,I did not get why is it safer to write(!list)

RUSHIT M JASANI @rmjasani 11 Jun 2017 07:52 pm

2 1 4 3 6 5 7 is right answer.

shweta @shweta1920 11 Jun 2017 08:00 pm

@rmjasani thank you for ur answer by I was asking for meaning of those lines which I asked after question

RUSHIT M JASANI @rmjasani 11 Jun 2017 08:26 pm

@shweta1920

!list means if list is null then true

And !list->next means if next list is null then true so any of the condition is true then it returns...