<?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>Pointer &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/pointer/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>PHP: Arrays or Linked Lists?</title>
		<link>/2012/07/24/php-arrays-or-linked-lists/</link>
		<comments>/2012/07/24/php-arrays-or-linked-lists/#comments</comments>
		<pubDate>Tue, 24 Jul 2012 11:25:20 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[data structures]]></category>
		<category><![CDATA[$_head]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[Comparison of programming languages]]></category>
		<category><![CDATA[Data structures]]></category>
		<category><![CDATA[Data types]]></category>
		<category><![CDATA[Extinction]]></category>
		<category><![CDATA[Foreach]]></category>
		<category><![CDATA[Linked list]]></category>
		<category><![CDATA[List]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Pointer]]></category>
		<category><![CDATA[Stack]]></category>
		<category><![CDATA[UnShuffle sort]]></category>

		<guid isPermaLink="false">/?p=3259</guid>
		<description><![CDATA[Arrays vs. Linked List If we talk about arrays and linked lists we know the pros and cons about both of them. No matter which programming language we use arrays benefit from direct access to its items, while linked lists are more memory efficient for particular tasks. The items of a linked list keep a &#8230; <a href="/2012/07/24/php-arrays-or-linked-lists/" class="more-link">Continue reading <span class="screen-reader-text">PHP: Arrays or Linked Lists?</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="/2012/07/17/computer-algorithms-detecting-and-breaking-a-loop-in-a-linked-list/" rel="bookmark" title="Computer Algorithms: Detecting and Breaking a Loop in a Linked List">Computer Algorithms: Detecting and Breaking a Loop in a 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/08/17/its-not-true-that-php-arrays-are-copied-by-value/" rel="bookmark" title="It&#8217;s Not True that PHP Arrays are Copied by Value">It&#8217;s Not True that PHP Arrays are Copied by Value </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Arrays vs. Linked List</h2>
<p>If we talk about arrays and linked lists we know the pros and cons about both of them. No matter which programming language we use arrays benefit from direct access to its items, while linked lists are more memory efficient for particular tasks.</p>
<figure id="attachment_3279" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/07/Array-Linked-List.png"><img src="/wp-content/uploads/2012/07/Array-Linked-List.png" alt="Array &amp; Linked List" title="Array &amp; Linked List" width="620" height="314" class="size-full wp-image-3279" srcset="/wp-content/uploads/2012/07/Array-Linked-List.png 620w, /wp-content/uploads/2012/07/Array-Linked-List-300x151.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Array &#038; Linked List</figcaption></figure>
<p>The items of a linked list keep a reference to their successor, so we can easily walk through the entire list. However we don&#8217;t have direct access to its elements. Thus we can&#8217;t go directly to its middle element! Even more &#8211; in particular implementations of a linked list we don&#8217;t know its length. But in some cases linked lists are far more effective than arrays. For instance reversing an array of non-numeric values require constant additional memory, but also requires n/2 exchanges. The same taks using linked lists is not only performed in linear time, but doesn&#8217;t require any additional memory. The only thing we need to do is to reverse the links &#8211; no movement of values and the items remain at the same place in the memory. </p>
<p>Merging of two arrays often require more space (proportional of the space of the two arrays) or many exchanges in case we try to do it in place. The same task on linked lists is far more effective with only changing pointers and without moving the values.<span id="more-3259"></span></p>
<h2>Arrays or Linked Lists are More Memory Efficient</h2>
<p>Many developers consider linked lists as something used only in college, but actually they can be very useful in practice as well. However how practically useful they are? Let&#8217;s see the following PHP experiment.</p>
<p>Here we have one class called &#8220;Item&#8221;, which is designed to keep only one integer value as its key and to point to its successor. Practically this class is designed to be used by a singly linked list, but let say we put some of these objects into an array and the same amount of the &#8220;Item&#8221; objects into a linked lists so what are the results?</p>
<p>First let&#8217;s see the code!</p>
<pre lang="PHP">
class Item
{
    protected $_key = '';
    protected $_next = null;
    
    public function __construct($key)
    {
        $this->_key = $key;
    }
    
    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 __toString()
    {
        return $this->_key . "\n";
    }
}
</pre>
<p>This is the &#8220;Item&#8221; class and here we have the Linked_List class. As you can see this is the very basic implementation of a linked list with only one &#8220;insert&#8221; method and the magic __toString() in order to print the entire list. The insert method pushes an item at the end of the list thus the insertion is O(1).</p>
<pre lang="PHP">
class Linked_List 
{
    protected $_head = null;
    protected $_tail = null;
    
    public function insert($item)
    {
        if ($this->_head == null) {
            $this->_head = $item;
            $this->_tail = $item;
            return;
        }
        
        $this->_tail->setNext($item);
        $this->_tail = $item;
    }
    
    public function __toString()
    {
        $current = $this->_head;
        $output = '';
        
        while ($current) {
            $output .= $current->getKey() . "\n";
            $current = $current->getNext();
        }
        
        return $output;
    }
}
</pre>
<p>Now let&#8217;s see the creation of an array with N objects of class &#8220;Item&#8221;.</p>
<pre lang="PHP">
$n = 10000;
$a = array();
for ($i = 0; $i < $n; $i++) {
    $a[$i] = new Item($i);
}
</pre>
<p>The same thing but using the Linked_List class follows on the lines below.</p>
<pre lang="PHP">
$n = 10000;
$a = new Linked_List();
for ($i = 0; $i < $n; $i++) {
    $a->insert(new Item($i));
}
</pre>
<h2>And the Winner is ...</h2>
<p>More memory efficient is ... the linked list! On the next chart we can see the results. It's clear that for 10K objects the array uses nearly 1MB more memory than the linked list! </p>
<figure id="attachment_3280" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/07/Array-vs.-Linked-List-Chart.png"><img src="/wp-content/uploads/2012/07/Array-vs.-Linked-List-Chart.png" alt="Array vs. Linked List Chart" title="Array vs. Linked List Chart" width="600" height="371" class="size-full wp-image-3280" srcset="/wp-content/uploads/2012/07/Array-vs.-Linked-List-Chart.png 600w, /wp-content/uploads/2012/07/Array-vs.-Linked-List-Chart-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>So what do you think now? Will you use linked list in your code or not?</p>
<h2>Final Words</h2>
<p>Although the linked list seems to be more memory efficient we don't have direct acess to it's items. In the same time often we don't need direct access, we just need to walk through the array, which doesn't benefit from the direct access. In PHP this is usally done with some loop construction as "foreach". So why we have such results in the experiment above. First our linked list is really very basic. It doesn't have any functionality, which in fact shouldn't affect memory usage much more. The array in the other hand keeps indexes for each of its items so this results in additional space. This explains a bit the victory of the linked list in the memory efficiency test.</p>
<p>In the other hand PHP can't have the full benefit of using linked lists, trees and other data structures since it keeps them in memory only for the request. In this case C, C++, Java loads a data structure in memory till the software runs so unfortunately coding complex data structures in PHP doesn't look as a great option. Indeed here we have an entire "Item" class only to keep an integer. Instead we can use an array of integers! </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="/2012/07/17/computer-algorithms-detecting-and-breaking-a-loop-in-a-linked-list/" rel="bookmark" title="Computer Algorithms: Detecting and Breaking a Loop in a Linked List">Computer Algorithms: Detecting and Breaking a Loop in a 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/08/17/its-not-true-that-php-arrays-are-copied-by-value/" rel="bookmark" title="It&#8217;s Not True that PHP Arrays are Copied by Value">It&#8217;s Not True that PHP Arrays are Copied by Value </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/07/24/php-arrays-or-linked-lists/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<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>
		<item>
		<title>Computer Algorithms: Linked List</title>
		<link>/2012/06/14/computer-algorithms-linked-list-data-structure/</link>
		<comments>/2012/06/14/computer-algorithms-linked-list-data-structure/#comments</comments>
		<pubDate>Thu, 14 Jun 2012 12:12:47 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[B-tree]]></category>
		<category><![CDATA[Bin]]></category>
		<category><![CDATA[Data structures]]></category>
		<category><![CDATA[Data types]]></category>
		<category><![CDATA[Hash table]]></category>
		<category><![CDATA[HEAD]]></category>
		<category><![CDATA[Insert]]></category>
		<category><![CDATA[John]]></category>
		<category><![CDATA[Linked list]]></category>
		<category><![CDATA[List]]></category>
		<category><![CDATA[Null]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Pointer]]></category>
		<category><![CDATA[public $head]]></category>
		<category><![CDATA[Smith]]></category>
		<category><![CDATA[SQL keywords]]></category>
		<category><![CDATA[Stack]]></category>

		<guid isPermaLink="false">/?p=3188</guid>
		<description><![CDATA[Introduction The linked list is a data structure in which the items are ordered in a linear way. Although modern programming languages support very flexible and rich libraries that works with arrays, which use arrays to represent lists, the principles of building a linked list remain very important. The way linked lists are implemented is &#8230; <a href="/2012/06/14/computer-algorithms-linked-list-data-structure/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Linked List</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/07/17/computer-algorithms-detecting-and-breaking-a-loop-in-a-linked-list/" rel="bookmark" title="Computer Algorithms: Detecting and Breaking a Loop in a Linked List">Computer Algorithms: Detecting and Breaking a Loop in a 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>The linked list is a data structure in which the items are ordered in a linear way. Although modern programming languages support very flexible and rich libraries that works with arrays, which use arrays to represent lists, the principles of building a linked list remain very important. The way linked lists are implemented is a ground level in order to build more complex data structures such as trees. </p>
<p>It&#8217;s true that almost every operation we can perform on a linked list can be done with an array. It&#8217;s also true that some operations can be faster on arrays compared to linked lists. </p>
<p>However understanding how to implement the basic operations of a linked list such as INSERT, DELETE, INSERT_AFTER, PRINT and so on is crucial in order to implement data structures as rooted trees, B-trees, red-black trees, etc.</p>
<h2>Overview</h2>
<p>Unlike arrays where we don’t have pointers to the next and the previous item, the linked list is designed to support such pointers. In some implementations there is only one pointer pointing to the successor of the item. This kind of data structures are called singly linked lists. In this case the the last element doesn’t have a successor, so the pointer to its next element usualy is NULL. However the most implemented version of a linked list supports two pointers. These are the so called doubly linked lists.</p>
<p><figure id="attachment_3197" style="width: 621px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/0.-Arrays-vs.-linked-list.png"><img src="/wp-content/uploads/2012/06/0.-Arrays-vs.-linked-list.png" alt="Arrays vs. linked list" title="Arrays vs. linked list" width="621" height="333" class="size-full wp-image-3197" srcset="/wp-content/uploads/2012/06/0.-Arrays-vs.-linked-list.png 621w, /wp-content/uploads/2012/06/0.-Arrays-vs.-linked-list-300x160.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a><figcaption class="wp-caption-text">Arrays items are defined by their indices, while the linked list item contains a pointer to its predecessor and his successor!</figcaption></figure><span id="more-3188"></span></p>
<p>Let’s take a look at some examples. Here’s an array:</p>
<pre lang="PHP">
A[2, 'hello', 'world', 13, 31]
</pre>
<p>We know that A[0] contains the number 2, while A[1] contains the word (string) &#8220;hello&#8221;. This is the very basic array representation where the indices are consecutive and start from 0.</p>
<p>In that case we know that if we’re looking at the item with index <strong>i</strong>, its next element has an index <strong>i+1</strong>, while his predecessor&#8217;s index is <strong>i-1</strong>. Thus we can easily iterate over items. However if we have an array with only 5 elements A[5] doesn’t exists, and in most of the cases is NULL. In other words array items are defined by their indices, and can be accessed directly with their index.</p>
<p>In the other hand most of the programming languages support associative arrays also called hash maps.</p>
<p>An associative array in PHP can be something like this.</p>
<pre lang="PHP">
$a = array(
	'hello' => 'world',
	31	=> 12,
	'b7'	=> 144,
);
</pre>
<p>Now because the indices are not consecutive integers we don’t know the successor and the predecessor of the current item. Yes, there is some internal pointer that can give us the link to the previous and the next item, but explicitly we can&#8217;t refer them.</p>
<p>Of course some libraries may have functions that can point us to the next item, such a function is <a href="http://php.net/manual/en/function.next.php" target="_blank">next()</a> in <a href="/category/php/">PHP</a>.</p>
<p>As we see arrays can replace the typical pointer-like representation of a linked list, but as I said already this data structure is crucial in order to understand more complex data structures.</p>
<p>Typically the linked list is implemented with two classes. The first one describing the item and the other one containing the main operations of the list such as search, insert, delete, etc.</p>
<p>The first class, typically called <strong>Item</strong> is a normal class containing various info about an item. In terms of persons, for instance, this class can contain the first and last names of the person, his address, phone etc. However it’s very important that this class contains pointers to its previous and its next objects.</p>
<p>In our terms each object of class Person will contain a pointer to a next object of the same class Person.</p>
<pre lang="PHP">
class Person
{
	public $next = null;
	public $prev = null;
	
	protected $_firstName = '';
	protected $_lastName = '';
	protected $_phone = '';
	
	
	public function __construct($firstName, $lastName, $phone)
	{
		$this->_firstName = $firstName;
		$this->_lastName = $lastName;
		$this->_phone = $phone;
	}
	
	public function __toString()
	{
		return 'First name: ' . $this->_firstName 
			 . ', Last name: ' . $this->_lastName 
			 . ', Phone: ' . $this->_phone;
	}
}
</pre>
<p>So we must first design the structure of an item. </p>
<p>The following thing to do is to define a linked list as an abstraction over a real world list, just like the stack and the queue. We can implement various operations for a linked list like <strong>insert</strong>, <strong>delete</strong>, <strong>insertBefore</strong>, <strong>insertAfter</strong>, <strong>sort</strong>, <strong>search</strong>, <strong>insertSorted</strong> etc. It’s up to the developer to decide which operations he wants to use. And of course this depends on the application.</p>
<h2>Implementation</h2>
<h3>Operations</h3>
<p>We can perform and define as much operations as we need. For instance we can code a linked list only with the basic insert, delete and print, but we can also go for insertBefore, insertAfter, deleteBefore, deleteAfter, insertSorted, which are described on the diagrams below.</p>
<h4>Insert</h4>
<p>Inserting in the front of a list seems much like inserting into a queue. In this case the new item becomes the head of the list and its successor is the previous head of the list.</p>
<figure id="attachment_3204" style="width: 619px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/1.-Insert-at-the-front-of-a-Linked-List.png"><img src="/wp-content/uploads/2012/06/1.-Insert-at-the-front-of-a-Linked-List.png" alt="Inserting at the front of a Linked List" title="Inserting at the front of a Linked List" width="619" height="346" class="size-full wp-image-3204" srcset="/wp-content/uploads/2012/06/1.-Insert-at-the-front-of-a-Linked-List.png 619w, /wp-content/uploads/2012/06/1.-Insert-at-the-front-of-a-Linked-List-300x167.png 300w" sizes="(max-width: 619px) 100vw, 619px" /></a><figcaption class="wp-caption-text">Inserting at the front of the list</figcaption></figure>
<pre lang="PHP">
class LList
{
	public $head;
	public $tail;
	
	public function insert($item) 
	{
		$item->next = $this->head;
		
		if ($this->head != null) {
			$this->head->prev = $item;
		}
		
		$this->head = $item;
	}

	public function __toString()
	{
		$cur = $this->head;
		
		$output = '';
		while ($cur) {
			$output .= $cur . ' ';
			
			$cur = $cur->next;
		}
		
		return $output . "\n";
	}
}

$ll = new LList();

$a = new Person('John', 'Smith', '555 9401');
$b = new Person('James', 'Johnes', '555 2454');

$ll->insert($a);
$ll->insert($b);

// James Johnes 555 2454
// John Smith 555 9401
echo $ll;
</pre>
<h4>Delete</h4>
<p>Delete the head of the list is much like deleting an item from a queue. However we can implement also deleting a custom element that&#8217;s inside the list.</p>
<figure id="attachment_3206" style="width: 618px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/4.-Delete-an-item.png"><img src="/wp-content/uploads/2012/06/4.-Delete-an-item.png" alt="Delete an item" title="Delete an item" width="618" height="362" class="size-full wp-image-3206" srcset="/wp-content/uploads/2012/06/4.-Delete-an-item.png 618w, /wp-content/uploads/2012/06/4.-Delete-an-item-300x175.png 300w" sizes="(max-width: 618px) 100vw, 618px" /></a><figcaption class="wp-caption-text">Deleting an item from the inside of the list!</figcaption></figure>
<pre lang="PHP">
class LList
{
	public $head;
	public $tail;
	
	public function insert($item) 
	{
		$item->next = $this->head;
		
		if ($this->head != null) {
			$this->head->prev = $item;
		}
		
		$this->head = $item;
	}
	
	public function delete($item) 
	{
		$cur = $this->head;
		
		while ($cur) {
			
			if ($cur == $item) {
				$prev = $cur->prev;
				$next = $cur->next;
				
				if ($prev != null) {
					$prev->next = $next;
				} else {
					// because head points to the first item
					$this->head = $next;
				}
				
				if ($next != null) {
					$next->prev = $prev;
				}
				
				return $cur;
			}
		
			$cur = $cur->next;
		}
	}

	public function __toString()
	{
		$cur = $this->head;
		
		$output = '';
		while ($cur) {
			$output .= $cur . ' ';
			
			$cur = $cur->next;
		}
		
		return $output . "\n";
	}
}

$ll = new LList();

$a = new Person('John', 'Smith', '555 9401');
$b = new Person('James', 'Johnes', '555 2454');
$c = new Person('Jeanne', 'Francois', '333 2323');

$ll->insert($a);
$ll->insert($b);
$ll->insert($c);

// prints objects $c, $b, $a:
// Jeanne Francois 333 2323
// James Johnes 555 2454
// John Smith 555 9401
echo $ll;

$ll->delete($b);

// prints objects $c, $a:
// Jeanne Francois 333 2323
// John Smith 555 9401
echo $ll;
</pre>
<h4>Insert before &#038; insert after</h4>
<p>Inserting before and after needs a reference to an already existing list item. After that the new object is inserted into it right place, as shown on the images below.</p>
<figure id="attachment_3208" style="width: 618px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/2.-Insert-after-a-given-item-of-a-Linked-List.png"><img src="/wp-content/uploads/2012/06/2.-Insert-after-a-given-item-of-a-Linked-List.png" alt="Insert after a given item of a Linked List" title="Insert after a given item of a Linked List" width="618" height="362" class="size-full wp-image-3208" srcset="/wp-content/uploads/2012/06/2.-Insert-after-a-given-item-of-a-Linked-List.png 618w, /wp-content/uploads/2012/06/2.-Insert-after-a-given-item-of-a-Linked-List-300x175.png 300w" sizes="(max-width: 618px) 100vw, 618px" /></a><figcaption class="wp-caption-text">Insert after splits the list after the pointed item and inserts the new object there!</figcaption></figure>
<pre lang="PHP">
class LList
{
	public $head;
	public $tail;
	
	public function insert($item) 
	{
		$item->next = $this->head;
		
		if ($this->head != null) {
			$this->head->prev = $item;
		}
		
		$this->head = $item;
	}
	
	public function insertAfter($newItem, $item) 
	{
		$cur = $this->head;
		while ($cur) {
			if ($cur == $item) {
				$next = $cur->next;
				
				$cur->next = $newItem;
				$newItem->prev = $cur;
				
				if ($next != null) {
					$newItem->next = $next;
					$next->prev = $newItem;
				}
				return;
			}
			$cur = $cur->next;
		}
		
		$this->head = $this->tail = $item;
	}

	public function __toString()
	{
		$cur = $this->head;
		
		$output = '';
		while ($cur) {
			$output .= $cur . ' ';
			
			$cur = $cur->next;
		}
		
		return $output . "\n";
	}
}

$ll = new LList();

$a = new Person('John', 'Smith', '555 9401');
$b = new Person('James', 'Johnes', '555 2454');
$c = new Person('Jeanne', 'Francois', '333 2323');

$ll->insert($a);
$ll->insert($c);

// inserts $b after $a
$ll->insertAfter($b, $c);

// Jeanne Francois 333 2323
// James Johnes 555 2454
// John Smith 555 9401
echo $ll;
</pre>
<p>Insert a new object before an item is the same as insert after, but instead of splitting the list after the given item, we split it before it.</p>
<figure id="attachment_3209" style="width: 618px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/3.-Insert-before-a-given-item-of-a-Linked-List.png"><img src="/wp-content/uploads/2012/06/3.-Insert-before-a-given-item-of-a-Linked-List.png" alt="Insert before a given item of a Linked List" title="Insert before a given item of a Linked List" width="618" height="362" class="size-full wp-image-3209" srcset="/wp-content/uploads/2012/06/3.-Insert-before-a-given-item-of-a-Linked-List.png 618w, /wp-content/uploads/2012/06/3.-Insert-before-a-given-item-of-a-Linked-List-300x175.png 300w" sizes="(max-width: 618px) 100vw, 618px" /></a><figcaption class="wp-caption-text">Insert before and insert after are very similar operations!</figcaption></figure>
<h4>Search</h4>
<p>Searching into a list can be modified depending on the application needs. Here we just compare the searched object with a list item.</p>
<a href="/wp-content/uploads/2012/06/5.-Search-for-an-item.png"><img src="/wp-content/uploads/2012/06/5.-Search-for-an-item.png" alt="Search for an item" title="Search for an item" width="620" height="258" class="size-full wp-image-3210" srcset="/wp-content/uploads/2012/06/5.-Search-for-an-item.png 620w, /wp-content/uploads/2012/06/5.-Search-for-an-item-300x124.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a>
<pre lang="PHP">
class LList
{
	public $head;
	public $tail;
	
	public function insert($item) 
	{
		$item->next = $this->head;
		
		if ($this->head != null) {
			$this->head->prev = $item;
		}
		
		$this->head = $item;
	}
	
	public function insertAfter($item, $key) 
	{
		$cur = $this->head;
		while ($cur) {
			if ($cur->data == $key) {
				$next = $cur->next;
				
				$cur->next = $item;
				$item->prev = $cur;
				
				if ($next != null) {
					$item->next = $next;
					$next->prev = $item;
				}
				return;
			}
			$cur = $cur->next;
		}
		
		$this->head = $this->tail = $item;
	}

	public function search($item)
	{
		$cur = $this->head;
		
		while ($cur) {
			if ($cur == $item) {
				return 1;
			}
			
			$cur = $cur->next;
		}
		
		return 0;
	}
	
	public function __toString()
	{
		$cur = $this->head;
		
		$output = '';
		while ($cur) {
			$output .= $cur . ' ';
			
			$cur = $cur->next;
		}
		
		return $output . "\n";
	}
}

$ll = new LList();

$a = new Person('John', 'Smith', '555 9401');
$b = new Person('James', 'Johnes', '555 2454');
$c = new Person('Jeanne', 'Francois', '333 2323');

$ll->insert($a);
$ll->insert($b);

// 1, because $b is in the list
echo $ll->search($b);

// 0, cause $c isn't in the list
echo $ll->search($c);
</pre>
<p>The operations here are only one sub-set of all possible operations you can implement on a linked list. It all depends on our needs. However the principles are important, so we can implement more complex data structures.</p>
<h2>Application</h2>
<p>It&#8217;s true that linked list are a very basic data structure. Someone may wonder why we should code and implement linked list since we can do the same (with almost every modern programming language/library) with arrays. The answer is that data structures as trees are difficult to implement with arrays, so it&#8217;s easy to code them using pointers. Thus linked lists is a ground level for understanding them. Indeed each linked list is a tree with only one branch as shown on the image below.</p>
<figure id="attachment_3213" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/6.-Linked-List-Trees.png"><img src="/wp-content/uploads/2012/06/6.-Linked-List-Trees.png" alt="Linked List &amp; Trees" title="Linked List &amp; Trees" width="620" height="399" class="size-full wp-image-3213" srcset="/wp-content/uploads/2012/06/6.-Linked-List-Trees.png 620w, /wp-content/uploads/2012/06/6.-Linked-List-Trees-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Each linked list is a single branch tree!</figcaption></figure>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/07/17/computer-algorithms-detecting-and-breaking-a-loop-in-a-linked-list/" rel="bookmark" title="Computer Algorithms: Detecting and Breaking a Loop in a Linked List">Computer Algorithms: Detecting and Breaking a Loop in a 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/06/14/computer-algorithms-linked-list-data-structure/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Stack and Queue</title>
		<link>/2012/06/05/computer-algorithms-stack-and-queue-data-structure/</link>
		<comments>/2012/06/05/computer-algorithms-stack-and-queue-data-structure/#comments</comments>
		<pubDate>Tue, 05 Jun 2012 09:54:13 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[$_head]]></category>
		<category><![CDATA[Abstract data type]]></category>
		<category><![CDATA[computer algorithms]]></category>
		<category><![CDATA[Data structures]]></category>
		<category><![CDATA[Extinction]]></category>
		<category><![CDATA[FALSE]]></category>
		<category><![CDATA[heapsort algorithm]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[LIFO]]></category>
		<category><![CDATA[Linked list]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Pointer]]></category>
		<category><![CDATA[Queue]]></category>
		<category><![CDATA[Shunting-yard algorithm]]></category>
		<category><![CDATA[Stack]]></category>
		<category><![CDATA[Subroutine]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[Web browser]]></category>
		<category><![CDATA[web programming]]></category>

		<guid isPermaLink="false">/?p=3173</guid>
		<description><![CDATA[Introduction Every developer knows that computer algorithms are tightly related to data structures. Indeed many of the algorithms depend on a data structures and can be very effective for some data structures and ineffective for others. A typical example of this is the heapsort algorithm, which depends on a data structure called “heap”. In this &#8230; <a href="/2012/06/05/computer-algorithms-stack-and-queue-data-structure/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Stack and Queue</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/07/16/friday-algorithms-a-data-structure-javascript-stack/" rel="bookmark" title="Friday Algorithms: A Data Structure: JavaScript Stack">Friday Algorithms: A Data Structure: JavaScript Stack </a></li>
<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="/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="/2017/09/14/data-structures-infographic-stack-queue/" rel="bookmark" title="Data Structures Infographic: Stack &#038; Queue">Data Structures Infographic: Stack &#038; Queue </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Every developer knows that <a href="/category/algorithms/" title="Algorithms on stoimen.com">computer algorithms</a> are tightly related to data structures. Indeed many of the algorithms depend on a data structures and can be very effective for some data structures and ineffective for others. A typical example of this is the heapsort algorithm, which depends on a data structure called “heap”. In this case although the stack and the queue are data structures instead of pure algorithms it&#8217;s imporant to understand their structure and the way they operate over data. </p>
<p>However, before we continue with the concrete realization of the stack and the queue, let’s first take a look on the definition of this term. A data structure is a logical abstraction that “models” the real world and presents (stores) our data in a specific format. The access to this data structure is often predefined thus we can access directly every item containing data. This help us to perform a different kind of tasks and operations over different kind of data structures &#8211; insert, delete, search, etc.. A typical data structures are the stack, the queue, the linked list and the tree.</p>
<p>All these structures help us perform specific operations effectively. For instance searching in a balanced tree is faster than searching in a linked list.</p>
<p>It is also very important to note that data structures can be represented in many different ways. We can model them using arrays or pointers, as shown in this post. In fact the most important thing is to represent the logical structure of the data structure you’re modeling. Thus the stack is a structure that follows the LIFO (Last In First Out) principle and it doesn’t matter how it is represented in our program (whether it will be coded with an array or with pointers). The important thing into a stack representation is to follow the LIFO principle correctly. In this case if the stack is an array only its top should be accessible and the only operation must be inserting new top of the stack.<br />
<span id="more-3173"></span></p>
<h2>Overview</h2>
<p>The stack and the queue are somehow related data structures as they represent two parts of somehow identical logics. Thus they are commonly described in pair.</p>
<h3>Stack</h3>
<p>The stack data structure models the real-world stack. You can think of it as stack of boxes one above the other. Thus the only way to put another item into the stack is to put it above all other items (on its top). This operation is often called “push”. In the other hand taking an item from the stack is called pop, and also only the highest item can be “poped”. The following image describes better the structure of the stack and its operations &#8211; push and pop.</p>
<figure id="attachment_3178" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/1.-Stack-Operations.png"><img src="/wp-content/uploads/2012/06/1.-Stack-Operations.png" alt="Stack Operations" title="Stack Operations" width="620" height="444" class="size-full wp-image-3178" srcset="/wp-content/uploads/2012/06/1.-Stack-Operations.png 620w, /wp-content/uploads/2012/06/1.-Stack-Operations-300x214.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">The operations of insert and delete an item from the stack are commonly called push and pop!</figcaption></figure>
<p>We see here how computer data structures model the real world. The stack data structure indeed makes no exception and models the real-world stacks.</p>
<h3>Stack Implementation</h3>
<p>As I said a stack can be implemented in some different ways. The first approach is to use an array (using the specific language syntax of the programming language of your choice). Here’s the implementation of a stack using an array in <a href="/category/php/" title="PHP on stoimen.com">PHP</a>.</p>
<pre lang="PHP">
$stack = array();

function push($data, &$stack) {
	$stack[] = $data;
}

function pop(&$stack)
{
	$len = count($stack);
	$top = $stack[$len-1];
	
	unset($stack[$len-1]);
	
	return $top;
}

// array()
print_r($stack);

push(1, $stack);
push(2, $stack);
push('some test', $stack);
push(array(25,12,1999), $stack);

// [1, 2, 'some test', [25, 12, 1999]]
print_r($stack);

// [25, 12, 1999]
echo pop($stack);
// 'some test'
echo pop($stack);

// [1, 2]
print_r($stack);
</pre>
<p>However there are much easier ways to do the same thing with PHP since there are lots of predefined functions that work with stacks.</p>
<pre lang="PHP">
$stack = array();

function push($data, &$stack) {
	$stack[] = $data;
}

function pop(&$stack)
{
	return array_pop($stack);
}

// array()
print_r($stack);

push(1, $stack);
push(2, $stack);
push('some test', $stack);
push(array(25,12,1999), $stack);

// [1, 2, 'some test', [25, 12, 1999]]
print_r($stack);

// [25, 12, 1999]
echo pop($stack);
// 'some test'
echo pop($stack);

// [1, 2]
print_r($ret);
</pre>
<p>As in many programming languages here the example makes use of integers but it can be modified to work with more complex data types as objects, mutli dimensional arrays, etc. However we can use a higher level abstraction in order to represent a stack. Here&#8217;s a short example of a stack using pointers. The stack class only holds a pointer to the top of the stack. Thus only the top can be &#8220;poped&#8221;. Also each elements points to its predecessor. Using this abstraction we&#8217;re sure that the programmer can perform only these two operations &#8211; &#8220;pop&#8221; and &#8220;push&#8221;.</p>
<pre lang="PHP">
class Struct
{
	protected $_data = null;
	protected $_next = null;
	
	public function __construct($data, $next)
	{
		$this->_data = $data;
		$this->_next = $next;
	}
	
	public function getData()
	{
		return $this->_data;
	}
	
	public function setData(&$data)
	{
		$this->_data = $data;
	}
	
	public function getNext()
	{
		return $this->_next;
	}
	
	public function setNext(&$next)
	{
		$this->_next = $next;
	}
}

class Stack
{
	protected $_top = null;
	
	public function push($data)
	{
		$item = new Struct($data, null);
		
		if ($this->_top == null) {
			$this->_top = $item;
		} else {
			$item->setNext($this->_top);
			$this->_top = $item;
		}
	}

	public function pop()
	{
		if ($this->_top) {
			$t = $this->_top;
			$data = $t->getData();
			
			$this->_top = $this->_top->getNext();
			
			$t = null;
			
			return $data;
		}
	}
	
	public function __toString()
	{
		$output = '';
		$t = $this->_top;
		while ($t) {
			$output .= $t->getData() . ' ';
			$t = $t->getNext();
		}
		
		return $output;
	}
}

$s = new Stack();
$s->push(1);
$s->push(2);
$s->push(3);

// 3 2 1
echo $s;

$s->pop();
$s->pop();

// 1
echo $s;
</pre>
<h3>Queue</h3>
<p>As mentioned above the queue is somehow related to the stack data structure. However it follows a different principle &#8211; FIFO (First In First Out), which means that the item that has been in the queue for the longest time is retrieved first.</p>
<figure id="attachment_3177" style="width: 618px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/2.-Queue-Operations.png"><img src="/wp-content/uploads/2012/06/2.-Queue-Operations.png" alt="Queue Operations" title="Queue Operations" width="618" height="232" class="size-full wp-image-3177" srcset="/wp-content/uploads/2012/06/2.-Queue-Operations.png 618w, /wp-content/uploads/2012/06/2.-Queue-Operations-300x112.png 300w" sizes="(max-width: 618px) 100vw, 618px" /></a><figcaption class="wp-caption-text">Inserting and deleting from a queue happen in the opposite sites of the queue!</figcaption></figure>
<p>This comes again from the real world, where we can think of a queue of people waiting in front of a movie theater. In this case the person that has waited the most takes its ticket first.</p>
<h3>Queue Implementation</h3>
<p>An array representation of a queue isn’t a difficult task. However the only example of a queue here is using pointers. Indeed the following code syntax is very tightly related to PHP so only the main principles of supporting a queue functionality is important.</p>
<pre lang="PHP">
class Item
{
	public $data = null;
	public $next = null;
	public $prev = null;
	
	public function __construct($data)
	{
		$this->data = $data;
	}
}

class Queue
{
	protected $_head = null;
	protected $_tail = null;
	
	public function insert($data)
	{
		$item = new Item($data);
		
		if ($this->_head == NULL) {
			$this->_head = $item;
		} else if ($this->_tail == NULL) {
			$this->_tail = $item;
			$this->_head->next = $this->_tail;
			$this->_tail->prev = $this->_head;
		} else {
			$this->_tail->next = $item;
			$item->prev = $this->_tail;
			$this->_tail = $item;
		}
	}
	
	public function delete()
	{
		if (isset($this->_head->data)) {
			
			$temp = $this->_tail;
			$data = $temp->data;
			
			$this->_tail = $this->_tail->prev;
			
			if (isset($this->_tail->next))
				$this->_tail->next = null;
			else 
				$this->_tail = $this->_head = null;
			
			return $data;
		}
		
		return FALSE;
	}
	
	public function __toString()
	{
		$output = '';
		$t = $this->_head;
		while ($t) {
			$output .= $t->data . ' | ';
			$t = $t->next;
		}
		
		return $output;
	}
}


$q = new Queue();

$q->insert(1);
$q->insert(2);
$q->insert(3);

// 1 2 3
echo $q;

$q->delete();
$q->delete();

// 1
echo $q;

$q->insert(15);
$q->insert('hello');
$q->insert('world');
$q->delete();

// 1 15 "hello"
echo $q;
</pre>
<h2>Application</h2>
<p>Stacks and queues are widely used in programming. By defining stacks and queues we somehow predefine the way our data structure is accessed, thus we&#8217;re sure that our program will access the data in a specific manner. For instance if we code a queue for a list or upcomming commands, we&#8217;re sure that the most waited command will be executed first. In this case we predefine the order the commands are processed. In the web programming, especially in JavaScript, every developer knows what&#8217;s an event fired in a web browser environemtn. In case of many events, they&#8217;re putted into a queue and they are executed consecutively in the order they were fired by the user.</p>
<p>Another example is the execution stack of most of the programming compilers and interpreters. We know that in a OOP languages, such as PHP for instance, there&#8217;s a stack of function calls. In case of failure we can easily see the &#8220;stack trace&#8221;.</p>
<p>You see how many examples of queues and stacks there are in the real-world programming. These two structures are easy to implement yet very important in order to understand other more complex data structures as linked lists and trees.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/07/16/friday-algorithms-a-data-structure-javascript-stack/" rel="bookmark" title="Friday Algorithms: A Data Structure: JavaScript Stack">Friday Algorithms: A Data Structure: JavaScript Stack </a></li>
<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="/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="/2017/09/14/data-structures-infographic-stack-queue/" rel="bookmark" title="Data Structures Infographic: Stack &#038; Queue">Data Structures Infographic: Stack &#038; Queue </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/06/05/computer-algorithms-stack-and-queue-data-structure/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
