<p>What's the best (halting) algorithm for determining if a linked list has a cycle in it?</p>

<p>[Edit] Analysis of asymptotic complexity for both time and space would be sweet so answers can be compared better.</p>

<p>[Edit] Original question was not addressing nodes with outdegree > 1, but there's some talk about it. That question is more along the lines of "Best algorithm to detect cycles in a directed graph".</p>

[{'answer_id': 34253, 'author': 'OysterD', 'author_id': 2638, 'author_profile': 'https://Stackoverflow.com/users/2638', 'pm_score': 0, 'selected': False, 'text': '<p>What about using a hash table to store the already seen nodes (you look at them in order from the start of the list)? In practise, you could achieve something close to O(N).</p>\n\n<p>Otherwise, using a sorted heap instead of a hash table would achieve O(N log(N)).</p>\n'}, {'answer_id': 34255, 'author': 'DrPizza', 'author_id': 2131, 'author_profile': 'https://Stackoverflow.com/users/2131', 'pm_score': 7, 'selected': True, 'text': '<p>Have two pointers iterating through the list; make one iterate through at twice the speed of the other, and compare their positions at each step.  Off the top of my head, something like:</p>\n\n<pre><code>node* tortoise(begin), * hare(begin);\nwhile(hare = hare-&gt;next)\n{\n    if(hare == tortoise) { throw std::logic_error("There\'s a cycle"); }\n    hare = hare-&gt;next;\n    if(hare == tortoise) { throw std::logic_error("There\'s a cycle"); }\n    tortoise = tortoise-&gt;next;\n}\n</code></pre>\n\n<p>O(n), which is as good as you can get.</p>\n'}, {'answer_id': 34258, 'author': 'Henrik Paul', 'author_id': 2238, 'author_profile': 'https://Stackoverflow.com/users/2238', 'pm_score': 0, 'selected': False, 'text': "<p>I wonder if there's any other way than just going iteratively - populate an array as you step forwards, and check if the current node is already present in the array...</p>\n"}, {'answer_id': 34277, 'author': 'Liedman', 'author_id': 890, 'author_profile': 'https://Stackoverflow.com/users/890', 'pm_score': 0, 'selected': False, 'text': "<p>Konrad Rudolph's algorithm won't work if the cycle isn't pointing to the beginning. The following list will make it an infinite loop: 1->2->3->2.</p>\n\n<p>DrPizza's algorithm is definitely the way to go.</p>\n"}, {'answer_id': 34285, 'author': 'DrPizza', 'author_id': 2131, 'author_profile': 'https://Stackoverflow.com/users/2131', 'pm_score': 0, 'selected': False, 'text': "<blockquote>\n  <p>In this case OysterD's code will be the fastest solution (vertex coloring)</p>\n</blockquote>\n\n<p>That would really surprise me.  My solution makes at most two passes through the list (if the last node is linked to the penultimate lode), and in the common case (no loop) will make only one pass.  With no hashing, no memory allocation, etc.</p>\n"}, {'answer_id': 34296, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 0, 'selected': False, 'text': "<blockquote>\n<blockquote>\n<p>In this case OysterD's code will be the fastest solution (vertex coloring)</p>\n</blockquote>\n<p>That would really surprise me. My solution makes at most two passes through the list (if the last node is linked to the penultimate lode), and in the common case (no loop) will make only one pass. With no hashing, no memory allocation, etc.</p>\n</blockquote>\n<p>Yes. I've noticed that the formulation wasn't perfect and have rephrased it. I still believe that a clever hashing might perform faster – by a hair. I believe your algorithm <em>is</em> the best solution, though.</p>\n<p>Just to underline my point: the vertec coloring is used to detect cycles in dependencies by modern garbage collectors so there is a very real use case for it. They mostly use bit flags to perform the coloring.</p>\n"}, {'answer_id': 140080, 'author': 'Guillermo Phillips', 'author_id': 441661, 'author_profile': 'https://Stackoverflow.com/users/441661', 'pm_score': 0, 'selected': False, 'text': "<p>You will have to visit every node to determine this.  This can be done recursively.  To stop you visiting already visited nodes, you need a flag to say 'already visited'.  This of course doesn't give you loops.  So instead of a bit flag, use a number.  Start at 1.  Check connected nodes and then mark these as 2 and recurse until the network is covered.  If when checking nodes you encounter a node which is more than one less than the current node, then you have a cycle.  The cycle length is given by the difference.</p>\n"}, {'answer_id': 6024103, 'author': 'kbsant', 'author_id': 500236, 'author_profile': 'https://Stackoverflow.com/users/500236', 'pm_score': 2, 'selected': False, 'text': '<p>Precondition: Keep track of the list size (update the size whenenver a node is added or deleted).</p>\n\n<p>Loop detection:</p>\n\n<ol>\n<li><p>Keep a counter when traversing the list size.</p></li>\n<li><p>If the counter exceeds the list size, there is a possible cycle.</p></li>\n</ol>\n\n<p>Complexity: O(n)</p>\n\n<p>Note: the comparison between the counter and the list size, as well as the update operation of the list size, must be made thread-safe.</p>\n'}, {'answer_id': 14070358, 'author': 'Harry He', 'author_id': 1092195, 'author_profile': 'https://Stackoverflow.com/users/1092195', 'pm_score': 0, 'selected': False, 'text': '<p>Two pointers are initialized at the head of list. One pointer forwards once at each step, and the other forwards twice at each step. If the faster pointer meets the slower one again, there is a loop in the list. Otherwise there is no loop if the faster one reaches the end of list.</p>\n\n<p>The sample code below is implemented according to this solution. The faster pointer is pFast, and the slower one is pSlow.</p>\n\n<pre><code>bool HasLoop(ListNode* pHead)\n{\n    if(pHead == NULL)\n        return false;\n\n\n    ListNode* pSlow = pHead-&gt;m_pNext;\n    if(pSlow == NULL)\n        return false;\n\n\n    ListNode* pFast = pSlow-&gt;m_pNext;\n    while(pFast != NULL &amp;&amp; pSlow != NULL)\n    {\n        if(pFast == pSlow)\n            return true;\n\n\n        pSlow = pSlow-&gt;m_pNext;\n\n\n        pFast = pFast-&gt;m_pNext;\n        if(pFast != NULL)\n            pFast = pFast-&gt;m_pNext;\n    }\n\n\n    return false;\n}\n</code></pre>\n\n<p>This solution is available on <a href="http://codercareer.blogspot.com/2012/01/no-29-loop-in-list.html" rel="nofollow">my blog</a>. There is a more problem discussed in the blog: What is the entry node when there is cycle/loop in a list?</p>\n'}, {'answer_id': 19701109, 'author': 'Ayrat', 'author_id': 801203, 'author_profile': 'https://Stackoverflow.com/users/801203', 'pm_score': 0, 'selected': False, 'text': '<p>"Hack" solution (should work in C/C++):</p>\n\n<ul>\n<li>Traverse the list, and set the last bit of <code>next</code> pointer to 1. </li>\n<li>If find an element with flagged pointer -- return true and the first element of the cycle. </li>\n<li>Before returning, reset pointers back, though i believe dereferencing will work even with flagged pointers.</li>\n</ul>\n\n<p>Time complexity is 2n. Looks like it doesn\'t use any temporal variables.</p>\n'}, {'answer_id': 31607956, 'author': 'mac jc', 'author_id': 4692908, 'author_profile': 'https://Stackoverflow.com/users/4692908', 'pm_score': 1, 'selected': False, 'text': '<p>Take 2 pointer *p and *q , start traversing the linked list "LL" using both pointers :</p>\n\n<p>1) pointer p will delete previous node each time and pointing to next node.</p>\n\n<p>2) pointer q will go each time in forward direction direction only.</p>\n\n<p>conditions:</p>\n\n<p>1) pointer p is pointing to null and q is pointing to some node : Loop is present</p>\n\n<p>2) both pointer pointing to null: no loop is there  </p>\n'}, {'answer_id': 38452940, 'author': 'FlyingAura', 'author_id': 3426358, 'author_profile': 'https://Stackoverflow.com/users/3426358', 'pm_score': 0, 'selected': False, 'text': '<p>This is a solution using a Hash table ( just a list actually) to save the pointer address. </p>\n\n<pre><code>def hash_cycle(node):\n    hashl=[]\n    while(node):\n        if node in hashl:\n            return True\n        else:\n            hashl.append(node)\n            node=node.next\n    return False\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/34249', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3594/']