795 views
1 votes
1 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;
   1: 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;
    }   
}

What is meant by line 1?

1 Answer

2 votes
2 votes
@hem chandraJoshi It means that if  the list is empty or the list has only 1 element then return.

!list is another way of saying list==NULL, both will return 1 if list is NULL. (negation of NULL is non-NULL, which in C is described as some non-zero value, and in most compilers is taken as 1, so !NULL is 1.)

!list->next is another way of saying !(list->next), as -> has higher priority. This condition checks that the next pointer of first node is NULL.

Related questions

0 votes
0 votes
2 answers
3
srestha asked Apr 29, 2019
740 views
Can somebody write the code or algorithm, how merge sort works efficiently in linked list? Is Heap sort most inefficient in Linked List Sorting? Elaborate plz
0 votes
0 votes
1 answer
4
Arnab Bhadra asked Jun 28, 2017
3,363 views
Insertion of a node into a doubly linked list requires how many changes to various Next and Previous Pointer?A. No ChangeB. 1 Next , 1 PreviousC. 2 Next , 2 PreviousD. 3 ...