How would you find a cycle in a linked list?
Answers were Sorted based on User's Feedback
Answer / sujith
Simultaneously go through the list by ones (slow iterator)
and by twos (fast iterator). If there is a loop the fast
iterator will go around that loop twice as fast as the slow
iterator. The fast iterator will lap the slow iterator
within a single pass through the cycle. Detecting a loop is
then just detecting that the slow iterator has been lapped
by the fast iterator.
This solution is "Floyd's Cycle-Finding Algorithm" as
published in "Non-deterministic Algorithms" by Robert W.
Floyd in 1967. It is also called "The Tortoise and the Hare
Algorithm"
| Is This Answer Correct ? | 11 Yes | 2 No |
Answer / 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 |
Answer / amit
the last node of the list will have address of first node
then it is a cycle linked list.
| Is This Answer Correct ? | 4 Yes | 11 No |
Will Macros support multiple arguments ?
array of pointer pointer to array pointer to pointer
c programs are converted into machine language with the help of a) an interpreter b) a compiler c) an operatinf system d) none of the above
State two uses of pointers in C?
Difference between macros and inline functions? Can a function be forced as inline?
0 Answers HAL, Honeywell, Zomato,
code for copying two strings with out strcpy() function.
What is return type in c?
write a program to sum of its digit with using control structure or with out using loop. for ex: let the number is 25634 then answer will be=2+5+6+3+4=20
Difference between exit() and _exit() function?
What is a memory leak? How to avoid it?
Which header file is essential for using strcmp function?
ABCDCBA ABC CBA AB BA A A