<?xml version="1.0" encoding="UTF-8" standalone="yes"?><oembed><version><![CDATA[1.0]]></version><provider_name><![CDATA[The ryg blog]]></provider_name><provider_url><![CDATA[https://fgiesen.wordpress.com]]></provider_url><author_name><![CDATA[fgiesen]]></author_name><author_url><![CDATA[https://fgiesen.wordpress.com/author/fgiesen/]]></author_url><title><![CDATA[Cycle detection algorithms are handy to&nbsp;know]]></title><type><![CDATA[link]]></type><html><![CDATA[<p>What the title says :). Just thought it was worth mentioning since I talked a bit about singly-linked lists in the <a href="https://fgiesen.wordpress.com/2010/09/27/data-structures-and-invariants/">&#8220;Data structures and invariants&#8221;</a> post, and cycles are the primary way that a singly-linked list can &#8220;go wrong&#8221; on you without containing invalid pointers: notably, you can get this if you try to insert some item <code>x</code> to a list when that list already contains <code>x</code>. (If you insert the &#8220;new&#8221; <code>x</code> before or at the position of the <code>x</code> that&#8217;s already in the list, you will get a cycle. If you insert it later, you will inadvertently remove all items between the old and new position).</p>
<p>When debugging this, it&#8217;s useful to have some cycle-detection code. You can add some fields to the list for debugging (not quite as trivial as it sounds, since clearing a &#8220;visited&#8221; flag involves traversing the list that might have a cycle &#8211; you need to make sure all fields are in a known &#8220;visited&#8221; state <em>before</em> you start looking for cycles if you do it this way), but a nicer solution that doesn&#8217;t require extra memory is to use a cycle detection algorithm. There are two main choices &#8211; Floyd&#8217;s &#8220;tortoise and hare&#8221; algorithm and Brent&#8217;s algorithm &#8211; and both are worth knowing about. They&#8217;re also explained well on <a href="http://en.wikipedia.org/wiki/Cycle_detection">Wikipedia</a>, so read up if you&#8217;ve never encountered them before.</p>
]]></html></oembed>