<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Linked &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/linked/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>on web development</description>
	<lastBuildDate>Tue, 13 Feb 2018 08:18:15 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.0.3</generator>
	<item>
		<title>Computer Algorithms: Detecting and Breaking a Loop in a Linked List</title>
		<link>/2012/07/17/computer-algorithms-detecting-and-breaking-a-loop-in-a-linked-list/</link>
		<comments>/2012/07/17/computer-algorithms-detecting-and-breaking-a-loop-in-a-linked-list/#comments</comments>
		<pubDate>Tue, 17 Jul 2012 07:43:05 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[$_head]]></category>
		<category><![CDATA[data]]></category>
		<category><![CDATA[Data structures]]></category>
		<category><![CDATA[Hare]]></category>
		<category><![CDATA[HEAD]]></category>
		<category><![CDATA[Infinite loop]]></category>
		<category><![CDATA[Linked]]></category>
		<category><![CDATA[Linked list]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Pointer]]></category>

		<guid isPermaLink="false">/?p=3243</guid>
		<description><![CDATA[Introduction Linked lists are one very common and handy data structure that can be used in many cases of the practical programming. In this post we&#8217;ll assume that we&#8217;re talking about singly linked list. This means that each item is pointed by it&#8217;s previous item and it points to it&#8217;s next item. In this scenario &#8230; <a href="/2012/07/17/computer-algorithms-detecting-and-breaking-a-loop-in-a-linked-list/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Detecting and Breaking a Loop in a Linked List</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/06/14/computer-algorithms-linked-list-data-structure/" rel="bookmark" title="Computer Algorithms: Linked List">Computer Algorithms: Linked List </a></li>
<li><a href="/2010/09/29/construct-a-sorted-php-linked-list/" rel="bookmark" title="Construct a Sorted PHP Linked List">Construct a Sorted PHP Linked List </a></li>
<li><a href="/2012/07/24/php-arrays-or-linked-lists/" rel="bookmark" title="PHP: Arrays or Linked Lists?">PHP: Arrays or Linked Lists? </a></li>
<li><a href="/2012/06/05/computer-algorithms-stack-and-queue-data-structure/" rel="bookmark" title="Computer Algorithms: Stack and Queue">Computer Algorithms: Stack and Queue </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Linked lists are one very common and handy data structure that can be used in many cases of the practical programming. In this post we&#8217;ll assume that we&#8217;re talking about singly linked list. This means that each item is pointed by it&#8217;s previous item and it points to it&#8217;s next item. In this scenario the first item of the list, its head, doesn&#8217;t have an ancestor and the last item doesn&#8217;t have a successor.</p>
<figure id="attachment_3260" style="width: 619px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/07/1.-Singly-Linked-List.png"><img class="size-full wp-image-3260" title="Singly Linked List" src="/wp-content/uploads/2012/07/1.-Singly-Linked-List.png" alt="Singly Linked List" width="619" height="158" srcset="/wp-content/uploads/2012/07/1.-Singly-Linked-List.png 619w, /wp-content/uploads/2012/07/1.-Singly-Linked-List-300x76.png 300w" sizes="(max-width: 619px) 100vw, 619px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>Sometimes, due to bugs or bad architecture or complexity of the applications we can have problems with lists. One very typical problem is having a loop, which in breve means that some of the items of the list is pointed twice, as shown on the image below.</p>
<figure id="attachment_3262" style="width: 618px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/07/2.-Loop-in-a-Singly-Linked-List.png"><img src="/wp-content/uploads/2012/07/2.-Loop-in-a-Singly-Linked-List.png" alt="Loop in a Singly Linked List" title="Loop in a Singly Linked List" width="618" height="247" class="size-full wp-image-3262" srcset="/wp-content/uploads/2012/07/2.-Loop-in-a-Singly-Linked-List.png 618w, /wp-content/uploads/2012/07/2.-Loop-in-a-Singly-Linked-List-300x119.png 300w" sizes="(max-width: 618px) 100vw, 618px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>So in first place we need to be sure that there is a loop and then: how can we break it!</p>
<p>There are several algorithms on finding a loop, but here’s one very basic. It’s known as the <a href="http://en.wikipedia.org/wiki/Robert_Floyd" title="Robert W. Floyd">Floyd</a>’s algorithm or the algorithm of the tortoise and hare.<span id="more-3243"></span></p>
<h2>Overview</h2>
<p>The Floyd’s algorithm relies on one very simple idea. Initially we set two pointers to the head of the list. </p>
<figure id="attachment_3265" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/07/3.-Tortoise-and-Hare.png"><img src="/wp-content/uploads/2012/07/3.-Tortoise-and-Hare.png" alt="Tortoise and Hare" title="Tortoise and Hare" width="620" height="399" class="size-full wp-image-3265" srcset="/wp-content/uploads/2012/07/3.-Tortoise-and-Hare.png 620w, /wp-content/uploads/2012/07/3.-Tortoise-and-Hare-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>On each step we increment both pointers, but the hare is incremented by two elements, while the tortoise walks on every single item &#8211; as shown on the images bellow.</p>
<figure id="attachment_3266" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/07/4.-Hare.png"><img src="/wp-content/uploads/2012/07/4.-Hare.png" alt="Hare" title="Hare" width="620" height="399" class="size-full wp-image-3266" srcset="/wp-content/uploads/2012/07/4.-Hare.png 620w, /wp-content/uploads/2012/07/4.-Hare-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">The hare is fast and jumps by a pair of items at once!</figcaption></figure>
<p>The tortoise, as it&#8217;s clear from the image bellow, is much slower.</p>
<figure id="attachment_3267" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/07/5.-Tortoise.png"><img src="/wp-content/uploads/2012/07/5.-Tortoise.png" alt="Tortoise" title="Tortoise" width="620" height="399" class="size-full wp-image-3267" srcset="/wp-content/uploads/2012/07/5.-Tortoise.png 620w, /wp-content/uploads/2012/07/5.-Tortoise-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">The tortoise is much slower than the hare!</figcaption></figure>
<p>As a result if we don’t have a loop in the list the hare will hit the end of the list, but if we do have a loop the hare will catch-up the tortoise inside the loop.</p>
<figure id="attachment_3268" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/07/6.-Movements.png"><img src="/wp-content/uploads/2012/07/6.-Movements.png" alt="Movements" title="Movements" width="620" height="399" class="size-full wp-image-3268" srcset="/wp-content/uploads/2012/07/6.-Movements.png 620w, /wp-content/uploads/2012/07/6.-Movements-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Since the hare is faster and both the hare and the tortoise are in the loop &#8211; the faster pointer will catch-up the tortoise!</figcaption></figure>
<h2>Code</h2>
<p>Assuming a typical representation of a singly linked list here’s a sample code in PHP.</p>
<h3>The Item Class</h3>
<pre lang="PHP">
class Item
{
    protected $_name = '';
    protected $_key = '';
    protected $_next = null;
    
    public function __construct($key, $name)
    {
        $this->_key = $key;
        $this->_name = $name;
    }
    
    public function setNext(&$next) { $this->_next = $next; }
    public function &getNext() { return $this->_next; }
    
    public function setKey($key) { $this->_key = $key; }
    public function getKey() { return $this->_key; }
    
    public function setName($name) { $this->_name = $name; }
    public function getName() { return $this->_name; }
    
    public function __toString()
    {
        return $this->_key . ' ' . $this->_name . "\n";
    }
}
</pre>
<h3>The List Class</h3>
<pre lang="PHP">
class Linked_List 
{
    protected $_head = null;
    
    public function insert($item)
    {
        if ($this->_head == null) {
            $this->_head = $item;
            return;
        }
        
        $current = $this->_head;
        while ($current->getNext()) {
            $current = $current->getNext();
        }
        
        $current->setNext($item);
    }
    
    public function detectLoop()
    {
        $tortoise = $hare = $this->_head;
        
        if ($hare->getNext() != null) {
            $hare = $hare->getNext()->getNext();
        } else {
            return FALSE;
        }
        
        while ($hare) {
            if ($hare == $tortoise) {
                return $hare;
            }
            
            if ($hare->getNext()) {
                $hare = $hare->getNext()->getNext();
            } else {
                return FALSE;
            }
            
            $tortoise = $tortoise->getNext();
        }
        
        return FALSE;
    }
    
    protected function _isReachable($a, $b) 
    {
        $current = $b;
        while ($current->getNext() != $b) {
            if ($current->getNext() == $a) {
                return $current;
            }
            $current = $current->getNext();
        }
        
        return FALSE;
    }
    
    public function breakLoop()
    {
        if (FALSE === ($loop = $this->detectLoop())) {
            return;
        }
        
        $startOfTheLoop = $this->_head;
        
        while (FALSE === ($lastLoopItem = $this->_isReachable($startOfTheLoop, $loop))) {
            $startOfTheLoop = $startOfTheLoop->getNext();
        }
        
        $pseudoNext = null;
        $lastLoopItem->setNext($pseudoNext);
    }
    
    public function __toString()
    {
        $current = $this->_head;
        $output = '';
        
        while ($current) {
            $output .= $current->getKey() . ' ' . $current->getName() . "\n";
            $current = $current->getNext();
        }
        
        return $output;
    }
}
</pre>
<h3>Initialization</p>
<h3>
<pre lang="PHP">
$items = array();
$ll = new Linked_List();

for ($i = 0; $i < 100; $i++) {
    $items[$i] = new Item($i, 'Item #' . $i);
    $ll->insert($items[$i]);
}

// 0 Item #0
// 1 Item #1
// ...
// 99 Item #99
echo $ll;
</pre>
<h2>Breaking the Loop</h2>
<p>In order to break the loop we need first to check whether an item is reachable from within the loop. Once we know that we should return the last loop item in order to improve the performance of the next method &#8211; breakLoop. This is made with the following method:</p>
<pre lang="PHP">
    protected function _isReachable($a, $b) 
    {
        $current = $b;
        while ($current->getNext() != $b) {
            if ($current->getNext() == $a) {
                return $current;
            }
            $current = $current->getNext();
        }
        
        return FALSE;
    }
</pre>
<p>Now we can break the loop by removing the double link to the first item of the loop. </p>
<pre lang="PHP">
    // member of Linked_List
    public function breakLoop()
    {
        if (FALSE === ($loop = $this->detectLoop())) {
            return;
        }
        
        $startOfTheLoop = $this->_head;
        
        while (FALSE === ($lastLoopItem = $this->_isReachable($startOfTheLoop, $loop))) {
            $startOfTheLoop = $startOfTheLoop->getNext();
        }
        
        $pseudoNext = null;
        $lastLoopItem->setNext($pseudoNext);
    }
</pre>
<h2>Complexity</h2>
<p>Assuming that the list length is N and the loop length is M, we&#8217;ll break the loop in O((N-M)*M) time complexity only after we&#8217;ve found the loop. The question is how fast we can find the loop with the algorithm above? Well the hare is pretty fast and can pass through some of the items of the loop several times, but the tortoise walks sequentially over all the items. The question is will the hare catch-up the tortoise before the last one gets to the end of the loop? The answer is yes and we can think of a single linked list without loops where there are two pointers starting from the beginning of the list. The same question can be translated to: will the faster pointer reach the end before the slower one gets to the middle of the list &#8211; well yes.</p>
<p>Finally the answer is O(N) for answering whether there&#8217;s a loop and O(M*(N-M)) to break it.</p>
<p>However the good news is that when we work with linked lists we often work only with pointers (which is our case in this post) and thus we don&#8217;t need additional memory which makes them very useful. Actually we will see the same advantage in the next algorithm &#8211; reversing a linked list, which is more effective than reversing an array.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/06/14/computer-algorithms-linked-list-data-structure/" rel="bookmark" title="Computer Algorithms: Linked List">Computer Algorithms: Linked List </a></li>
<li><a href="/2010/09/29/construct-a-sorted-php-linked-list/" rel="bookmark" title="Construct a Sorted PHP Linked List">Construct a Sorted PHP Linked List </a></li>
<li><a href="/2012/07/24/php-arrays-or-linked-lists/" rel="bookmark" title="PHP: Arrays or Linked Lists?">PHP: Arrays or Linked Lists? </a></li>
<li><a href="/2012/06/05/computer-algorithms-stack-and-queue-data-structure/" rel="bookmark" title="Computer Algorithms: Stack and Queue">Computer Algorithms: Stack and Queue </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/07/17/computer-algorithms-detecting-and-breaking-a-loop-in-a-linked-list/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
