1,358 views
5 votes
5 votes

Consider the following code which is used to detect the loop in the linked list. Find the missing statement A?

p = head;
q = head->next;
while(A)
{
    if(p == q) exit(0) //loop detected
    p = p->next;
    q = (q->next)?(q->next->next) : q->next;
}

Which of the following are correct statements

a) p!=NULL

b) q!=NULL

c) (p!=NULL) && (q!=NULL)

d) (p!=NULL) || (q!=NULL)

Given ans is c.......but I think b could also be correct if not than why..... Please explain

1 Answer

4 votes
4 votes

Actually , here p and q  pointer is incrementing 1:3 manner. As p is incrementing very less than q , so, loop will exists when q coming back and address of q pointer will match with p pointer.

So, we can tell if there is no loop, q will go end of list first and will accept

q==NULL

and will terminate

Otherwise p and q both get a valid pointer value and keep moving.

So, only checking of q pointer will be sufficient and enough

Ans will be B)

Related questions

0 votes
0 votes
1 answer
3
Arnab Bhadra asked Jun 28, 2017
3,357 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 ...