<?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>Subroutine &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/subroutine/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: 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>
		<item>
		<title>OOP JavaScript: Accessing Public Methods in Private Methods</title>
		<link>/2011/07/28/oop-javascript-accessing-public-methods-in-private-methods/</link>
		<comments>/2011/07/28/oop-javascript-accessing-public-methods-in-private-methods/#comments</comments>
		<pubDate>Thu, 28 Jul 2011 12:05:42 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[web development]]></category>
		<category><![CDATA[Accessing Private]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[Class]]></category>
		<category><![CDATA[Computer programming]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Curly bracket programming languages]]></category>
		<category><![CDATA[JavaScript programming language]]></category>
		<category><![CDATA[Object-oriented programming]]></category>
		<category><![CDATA[oop]]></category>
		<category><![CDATA[private]]></category>
		<category><![CDATA[public]]></category>
		<category><![CDATA[Scripting languages]]></category>
		<category><![CDATA[Software engineering]]></category>
		<category><![CDATA[Subroutine]]></category>

		<guid isPermaLink="false">/?p=2339</guid>
		<description><![CDATA[As you know in JavaScript when you define a variable with the special word &#8220;var&#8221; the scope of this variable is within the function. So when you simply wite &#8220;var a = 5&#8221; the variable named &#8220;a&#8221; has a global scope and can be accessed in any function in the global scope. var a = &#8230; <a href="/2011/07/28/oop-javascript-accessing-public-methods-in-private-methods/" class="more-link">Continue reading <span class="screen-reader-text">OOP JavaScript: Accessing Public Methods in Private Methods</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2011/05/30/object-oriented-javascript-inheritance/" rel="bookmark" title="Object Oriented JavaScript: Inheritance">Object Oriented JavaScript: Inheritance </a></li>
<li><a href="/2011/10/20/some-notes-on-the-object-oriented-model-of-php/" rel="bookmark" title="Some Notes on the Object-oriented Model of PHP">Some Notes on the Object-oriented Model of PHP </a></li>
<li><a href="/2010/08/11/quick-look-at-javascript-objects/" rel="bookmark" title="Quick Look at JavaScript Objects">Quick Look at JavaScript Objects </a></li>
<li><a href="/2010/03/09/what-make-javascript-closures-work/" rel="bookmark" title="What make JavaScript closures work?">What make JavaScript closures work? </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>As you know in JavaScript when you define a variable with the special word &#8220;var&#8221; the scope of this variable is within the function. So when you simply wite &#8220;var a = 5&#8221; the variable named &#8220;a&#8221; has a global scope and can be accessed in any function in the global scope. </p>
<pre lang="javascript">
var a = 5;

function f() { return a; } // returns 5
</pre>
<p>Thus f will return the value of &#8220;a&#8221; which equals to 5. You can also change the value of the global variable in the function body.</p>
<pre lang="javascript">
var a = 5;
function f() { a = 10; return a; }
console.log(a); // equals to 10
</pre>
<p>Now after we call the function f the value of &#8220;a&#8221; will equal to 10. This is because we reference the global variable &#8220;a&#8221; into the function body without using the keyword &#8220;var&#8221;. This means that if you put the &#8220;var&#8221; keyword the variable &#8220;a&#8221; inside the function body is no longer the same variable as the variable defined outside the body. It becames &#8220;local&#8221; and it&#8217;s visible only inside the function.<br />
<span id="more-2339"></span></p>
<h2>Objects &#038; JavaScript</h2>
<p>Actually in JavaScript functions can be also objects. Any variable defined with the &#8220;var&#8221; keyword becomes private, because it&#8217;s only visible inside the function body, while by using the &#8220;this&#8221; keyword we can define global variables visible outside the function body. Let&#8217;s see na example.</p>
<pre lang="javascript">
var f = function() 
{
	var a = 10;
	this.b = 5;
}

var myfunc = new f();
myfunc.a; // is undefined because a is private
myfunc.b; // equals to 5 because b is public
</pre>
<h2>Public and Private Methods in JavaScript</h2>
<p>As you may know in JS you can define functions inside other functions. Actually this is how you can define classes in JavaScript.</p>
<pre lang="javascript">
var myClass = function() 
{
	var f = function() {
		return 10;
	}
}
</pre>
<p>But this in fact defines a local (private) function into myClass and we cannot access it from the outside world. Here&#8217;s a fully functional class with one public and one private method.</p>
<pre lang="javascript">
var myClass = function()
{
	// public method
	this.a = function() {
		return 10;
	}
	
	// private method
	var b = function() {
		return 5;
	}
}

var c = new myClass();
c.a(); // will return 10
c.b(); // is undefined, because is private
</pre>
<h2>Accessing Private Methods from Public Methods</h2>
<p>Easily we can access private methods from public ones.</p>
<pre lang="javascript">
var myClass = function()
{
	// public method
	this.a = function() {
		return b();
	}
	
	// private method
	var b = function() {
		return 5;
	}
}
</pre>
<p>However accessing public mtehods in private ones is more difficult. That&#8217;s because we cannot use &#8220;this&#8221; into the private methods, just because &#8220;this&#8221; refers to the private method<br />
itself and not to the global method, which is &#8220;myClass&#8221; in our case.</p>
<pre lang="javascript">
var myClass = function()
{
	// public method
	this.a = function() {
		return 10;
	}
	
	// private method
	var b = function() {
		return this.a(); // this will result in an error
	}
}
</pre>
<h2>Accessing Public Methods from Private Methods</h2>
<p>To access public methods in private methods you need to define a variable that points to the global &#8220;this&#8221; object.</p>
<pre lang="javascript">
var myClass = function()
{
	var self = this; 
	
	// public method
	this.a = function() {
		return 10;
	}
	
	// private method
	var b = function() {
		return self.a(); // this will return 10
	}
}
</pre>
<p>This variable gives you the bridge between private methods and global &#8220;this&#8221; pointer.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2011/05/30/object-oriented-javascript-inheritance/" rel="bookmark" title="Object Oriented JavaScript: Inheritance">Object Oriented JavaScript: Inheritance </a></li>
<li><a href="/2011/10/20/some-notes-on-the-object-oriented-model-of-php/" rel="bookmark" title="Some Notes on the Object-oriented Model of PHP">Some Notes on the Object-oriented Model of PHP </a></li>
<li><a href="/2010/08/11/quick-look-at-javascript-objects/" rel="bookmark" title="Quick Look at JavaScript Objects">Quick Look at JavaScript Objects </a></li>
<li><a href="/2010/03/09/what-make-javascript-closures-work/" rel="bookmark" title="What make JavaScript closures work?">What make JavaScript closures work? </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2011/07/28/oop-javascript-accessing-public-methods-in-private-methods/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Friday Algorithms: A Data Structure: JavaScript Stack</title>
		<link>/2010/07/16/friday-algorithms-a-data-structure-javascript-stack/</link>
		<comments>/2010/07/16/friday-algorithms-a-data-structure-javascript-stack/#respond</comments>
		<pubDate>Fri, 16 Jul 2010 11:02:40 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[web development]]></category>
		<category><![CDATA[Abstract data type]]></category>
		<category><![CDATA[Computer programming]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Control flow]]></category>
		<category><![CDATA[Data structures]]></category>
		<category><![CDATA[Data types]]></category>
		<category><![CDATA[Linked list]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[Software engineering]]></category>
		<category><![CDATA[Stack]]></category>
		<category><![CDATA[Subroutine]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[Tree traversal]]></category>

		<guid isPermaLink="false">/?p=1713</guid>
		<description><![CDATA[Algorithms and Data Structures Instead of writing about &#8220;pure&#8221; algorithms this time I&#8217;ve decided to write about data structures and to start with a stack implementation in JavaScript. However algorithms and data structures live together since the very beginning of the computer sciences. Another reason to write about data structures is that many algorithms need &#8230; <a href="/2010/07/16/friday-algorithms-a-data-structure-javascript-stack/" class="more-link">Continue reading <span class="screen-reader-text">Friday Algorithms: A Data Structure: JavaScript Stack</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/06/18/friday-algorithms-iterative-quicksort/" rel="bookmark" title="Friday Algorithms: Iterative Quicksort">Friday Algorithms: Iterative Quicksort </a></li>
<li><a href="/2010/06/11/friday-algorithms-quicksort-difference-between-php-and-javascript/" rel="bookmark" title="Friday Algorithms: Quicksort &#8211; Difference Between PHP and JavaScript">Friday Algorithms: Quicksort &#8211; Difference Between PHP and JavaScript </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>
<li><a href="/2010/07/02/friday-algorithms-javascript-merge-sort/" rel="bookmark" title="Friday Algorithms: JavaScript Merge Sort">Friday Algorithms: JavaScript Merge Sort </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Algorithms and Data Structures</h2>
<p><a href="/wp-content/uploads/2010/06/stack.jpg"><img class="aligncenter size-full wp-image-1721" title="stack" src="/wp-content/uploads/2010/06/stack.jpg" alt="stack" width="430" height="286" srcset="/wp-content/uploads/2010/06/stack.jpg 430w, /wp-content/uploads/2010/06/stack-300x199.jpg 300w" sizes="(max-width: 430px) 100vw, 430px" /></a></p>
<p>Instead of writing about &#8220;pure&#8221; algorithms this time I&#8217;ve decided to write about data structures and to start with a stack implementation in JavaScript. However algorithms and data structures live together since the very beginning of the computer sciences. Another reason to write about data structures is that many algorithms need a specific data structure to be implemented. Most of the search algorithms are data structure dependent. You know that searching into a tree is different from searching into a linked list.</p>
<p>I&#8217;d like to write more about searching in my future algorithm posts, but first we need some data structure examples. The first one is, as I mentioned &#8211; <a href="http://en.wikipedia.org/wiki/Stack_%28data_structure%29">stack</a>.</p>
<p>Implemented in JavaScript this is really a simple example, which don&#8217;t need much to be understood. But in first place what is a stack?</p>
<p>You can thing of the &#8220;computer science&#8221; stack as a stack of sheets of paper, as it&#8217;s shown on the picture. You&#8217;ve three basic operations. You can add new element to the stack by putting it on the top of the stack, so the previous top of the stack becomes the second element in the stack. Another operation is to &#8220;pop&#8221; from the stack &#8211; remove the &#8220;first&#8221; element in the stack &#8211; the top most element, and to return it. And finally print the stack. This is difficult to define as an operation, but let say you&#8217;ve to show somehow every element from the stack.</p>
<p>Here&#8217;s a little diagram:</p>
<p><a href="/wp-content/uploads/2010/07/stack.png"><img class="alignleft size-full wp-image-1837" title="stack" src="/wp-content/uploads/2010/07/stack.png" alt="Stack" width="378" height="130" srcset="/wp-content/uploads/2010/07/stack.png 378w, /wp-content/uploads/2010/07/stack-300x103.png 300w" sizes="(max-width: 378px) 100vw, 378px" /></a></p>
<h2>Source Code</h2>
<p>At the end some source code:</p>
<pre lang="javascript">
var node = function()
{
    var data;
    var next = null;
}

var stack = function()
{
    this.top = null;

    this.push = function(data) {
        if (this.top == null) {
            this.top = new node();
            this.top.data = data;
        } else {
            var temp = new node();
            temp.data = data;
            temp.next = this.top;
            this.top = temp;
        }
    }

    this.pop = function() {
        var temp = this.top;
        var data = this.top.data;
        this.top = this.top.next;
        temp = null;
        return data;
    }

    this.print = function() {
        var node = this.top;
        while (node != null) {
            console.log(node.data);
            node = node.next;
        }
    }
}

var s = new stack();

s.push(1);
s.push(2);
s.push(3);

s.print();

var a = s.pop();

s.print();
</pre>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/06/18/friday-algorithms-iterative-quicksort/" rel="bookmark" title="Friday Algorithms: Iterative Quicksort">Friday Algorithms: Iterative Quicksort </a></li>
<li><a href="/2010/06/11/friday-algorithms-quicksort-difference-between-php-and-javascript/" rel="bookmark" title="Friday Algorithms: Quicksort &#8211; Difference Between PHP and JavaScript">Friday Algorithms: Quicksort &#8211; Difference Between PHP and JavaScript </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>
<li><a href="/2010/07/02/friday-algorithms-javascript-merge-sort/" rel="bookmark" title="Friday Algorithms: JavaScript Merge Sort">Friday Algorithms: JavaScript Merge Sort </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/07/16/friday-algorithms-a-data-structure-javascript-stack/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
