How would you find a cycle in a linked list?

Answer Posted / jaroosh

The above method is working of course, but is not the most
efficient. Other methods are however quite complex and not
so easy to explain.
Anyway, to exemplify this aforementioned method, maybe not
the most efficient code, but off the top of my head, hope
there are no misspellings.

bool isCyclic(LinkedNode *list)
{
if(list == NULL || list->next == NULL) return false;
LinkedNode *node1 = list, *node2 = node1->next;
while(node1 != node2)
{
if(node1==NULL || node2==NULL || node2->next == NULL)
return false;
node1 = node1->next;
node2= node2->next->next;
}
return true;
}

NOTE: the assumption is that for noncyclic list, the last
node has next pointer set to NULL.

Is This Answer Correct ?    6 Yes 7 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What are the 3 types of structures?

562


Explain how do you override a defined macro?

577


What is the difference between ā€˜gā€™ and ā€œgā€ in C?

2495


What is volatile variable in c with example?

579


can any one tel me wt is the question pattern for NIC exam

1551






What is the difference between procedural and declarative language?

640


What is the use of a static variable in c?

585


Is main is a keyword in c?

602


Program to find the sum of digits of a given number until the sum becomes a single digit. (e.g. 12345=>1+2+3+4+5=15=>1+5=6)

683


Explain what are reserved words?

630


What is pointer to pointer in c language?

589


How is a structure member accessed?

581


Explain what is page thrashing?

603


in any language the sound structure of that language depends on its a) character set, input/output function, its control structures b) character set, library functions, input/output functions its control structures c) character set, library functions, control sturctures d) character set, operators, its control structures

672


What the advantages of using Unions?

667