<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Stacks - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Stacks - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Thu, 25 Jun 2026 10:03:03 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/stacks/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ A Gentle Introduction to Data Structures: How Queues Work ]]>
                </title>
                <description>
                    <![CDATA[ By Michael Olorunnisola Black Friday’s right around the corner, and the new Microsoft Surface Studio out in stores (I’m a loyal windows guy ?). So let’s talk about everyone’s favorite shopping past-time: waiting in line. And that age-old data structu... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/a-gentle-introduction-to-data-structures-how-queues-work-f8b871938e64/</link>
                <guid isPermaLink="false">66c3429d42d4db64acf4cbaa</guid>
                
                    <category>
                        <![CDATA[ data structures ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ queue ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Software Engineering ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Stacks ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sun, 06 Nov 2016 04:38:49 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*vQPzNuz_TAOwQAkBfuaC6A.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Michael Olorunnisola</p>
<p>Black Friday’s right around the corner, and the new Microsoft Surface Studio out in stores (I’m a loyal windows guy ?). So let’s talk about everyone’s favorite shopping past-time: waiting in line. And that age-old data structure, the queue.</p>
<p>Feel free to share this post with your friends who’ll be heading out to get the latest and greatest. But be warned — people have been known to forget how queues work on Black Friday.</p>
<h3 id="heading-queues">Queues</h3>
<p>A queue is a line (yep, the same one from kindergarten…no cutting still!)</p>
<p>Additions (<strong>enqueues</strong>) always add to the back of the line</p>
<p>Removals (<strong>dequeues</strong>) always remove from the front of the line</p>
<p>Queues follow the pattern of <strong>F</strong>irst item <strong>I</strong>n is the <strong>F</strong>irst item <strong>O</strong>ut (FIFO).</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/GMjTKmWR6yBI5GEXVEnsZ81dlQHLK5L2dKei" alt="Image" width="300" height="196" loading="lazy"></p>
<h4 id="heading-example-use-cases"><strong>Example use cases</strong></h4>
<ul>
<li>Resolving simultaneous server requests from multiple users, such as 3 people buying the last ticket for a plane at almost the same time</li>
<li>Queuing up data during a <a target="_blank" href="https://en.wikipedia.org/wiki/Breadth-first_search">breadth-first search</a>.</li>
</ul>
<p>Let’s tackle the first use case by helping Microsoft create a queue data structure to manage all their requests for the new Surface Studio. I’m too busy coding and writing these posts to go get one myself, so if you’re a Microsoft representative reading this, please feel free to ship one my way. ?</p>
<p>Before we get started, a quick note on JavaScript arrays. Similar to <a target="_blank" href="https://medium.freecodecamp.com/data-structures-stacks-on-stacks-c25f2633c529#.cj82kpcg8">stacks</a>, JavaScript arrays naturally have the functionality of a queue built in.</p>
<h3 id="heading-how-to-represent-queues-using-javascript-arrays">How to represent queues using JavaScript arrays</h3>
<p><strong>Enqueue</strong> adds to the back of the array:</p>
<pre><code><span class="hljs-built_in">Array</span>.push(someVal)
</code></pre><p><strong>Dequeue</strong> removes and returns first item in array:</p>
<pre><code><span class="hljs-built_in">Array</span>.shift()
</code></pre><p>If for some reason you’re feeling rebellious (what coder doesn’t ?) you could add to the front of the array, then remove from the back.</p>
<p><strong>Enqueue</strong> adds item to the front of the array:</p>
<pre><code><span class="hljs-built_in">Array</span>.unshift(someVal)
</code></pre><p><strong>Dequeue</strong> removes item from the back of the array:</p>
<pre><code><span class="hljs-built_in">Array</span>.pop()
</code></pre><p>That said, for the sake of being thorough, you’re going to rebuild it using a JavaScript Object.</p>
<p>So first thing you need to do for Microsoft is to create the actual Queue where you’re going to hold the individual members who click the buy button on their website.</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Queue</span></span>{  <span class="hljs-keyword">constructor</span>(){    <span class="hljs-built_in">this</span>._storage = {};    <span class="hljs-built_in">this</span>._start = <span class="hljs-number">-1</span>; <span class="hljs-comment">//replicating 0 index used for arrays    this._end = -1; //replicating 0 index used for arrays  }    size(){   return this._end - this._start;  }}</span>
</code></pre><pre><code><span class="hljs-keyword">let</span> appleQueue = <span class="hljs-keyword">new</span> Queue();
</code></pre><p>As a quick reminder the _ just means this is a private variable, and shouldn’t be accessed directly.</p>
<p>Unlike the <a target="_blank" href="https://medium.freecodecamp.com/data-structures-stacks-on-stacks-c25f2633c529#.cj82kpcg8">stack data structure</a>, where additions and removals happen on the same side, the nature of the queue requires us to keep track of both ends. Because of that, you create the start variable to always track the front of the queue, and the end variable to track the end of the queue.</p>
<p>Lastly, the easiest way to keep track of a queue’s size (without creating an unnecessary counter variable) is to keep track of the difference between your start and end points.</p>
<p>First, you should create a way for people who click buy to be added to the queue. You can do this via the enqueue method:</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Queue</span></span>{  <span class="hljs-keyword">constructor</span>(){    <span class="hljs-built_in">this</span>._storage = {};    <span class="hljs-built_in">this</span>._start = <span class="hljs-number">-1</span>; <span class="hljs-comment">//replicating 0 index used for arrays    this._end = -1; //replicating 0 index used for arrays  }    enqueue(val){    this._storage[++this._end] = val;          //++this._end just means increment the end variable first    //It's equivalent to    //this._end++   //-&gt;    //this._storage[this._end] = val;  }    size(){   return this._end - this._start;  }}</span>
</code></pre><pre><code><span class="hljs-keyword">let</span> microsoftQueue = <span class="hljs-keyword">new</span> Queue();
</code></pre><pre><code>microsoftQueue.enqueue(<span class="hljs-string">"{user: ILoveWindows@gmail.com}"</span>)microsoftQueue.enqueue(<span class="hljs-string">"{user: cortanaIsMyBestFriend@hotmail.com}"</span>)microsoftQueue.enqueue(<span class="hljs-string">"{user: InternetExplorer8Fan@outlook.com}"</span>)microsoftQueue.enqueue(<span class="hljs-string">"{user: IThrowApplesOutMyWindow@yahoo.com}"</span>)
</code></pre><p>Great! Now your microsoftQueue storage is going to look a little something like this:</p>
<pre><code>{
</code></pre><pre><code>  <span class="hljs-number">0</span>: <span class="hljs-string">"{email: ILoveWindows@gmail.com}"</span>
</code></pre><pre><code>  <span class="hljs-number">1</span>: <span class="hljs-string">"{email: cortanaIsMyBestFriend@hotmail.com}"</span>
</code></pre><pre><code>  <span class="hljs-number">2</span>: <span class="hljs-string">"{email: InternetExplorer8Fan@outlook.com}"</span>
</code></pre><pre><code>  <span class="hljs-number">3</span>: <span class="hljs-string">"{email: IThrowApplesOutMyWindow@yahoo.com}"</span>
</code></pre><pre><code>}
</code></pre><p>So a quick note on the way users are being represented above ({user: …}).</p>
<p>When a user clicks the buy button on the client side, they’re sending all their relevant information to the server, which will handle the request. When data is often exchanged between systems, such as the client and server side, it’s most commonly sent as <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON">JSON</a> (<strong>J</strong>ava<strong>S</strong>cript <strong>O</strong>bject <strong>N</strong>otation), via <a target="_blank" href="http://www.w3schools.com/xml/ajax_intro.asp">Ajax</a>.</p>
<p>This is similar to JavaScript objects, in that it’s just a stringified version of key-value pairs. For those not familiar with JavaScript, it’s similar to a dictionary or hash table (which we’ll get to later in this series). For more information about this , there’s a great post <a target="_blank" href="http://stackoverflow.com/questions/383692/what-is-json-and-why-would-i-use-it">here</a> on StackOverflow by Andreas Grech.</p>
<p>Now back to your queue.</p>
<p>Thanks to the queue you created, Microsoft now has an efficient way of tracking all of the people who have purchased the Surface Studio, and in chronological order in which they purchased it. To make sure these people are served in the correct order, you need to create an accurate dequeue method that keeps track of the order of the buyers, and removes them from the queue once they’ve been served.</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Queue</span></span>{  <span class="hljs-keyword">constructor</span>(){    <span class="hljs-built_in">this</span>._storage = {};    <span class="hljs-built_in">this</span>._start = <span class="hljs-number">-1</span>; <span class="hljs-comment">//replicating 0 index used for arrays    this._end = -1; //replicating 0 index used for arrays  }    enqueue(val){    this._storage[++this._end] = val;   }</span>
</code></pre><pre><code>  dequeue(){    <span class="hljs-keyword">if</span>(<span class="hljs-built_in">this</span>._end &gt; <span class="hljs-built_in">this</span>._start){ <span class="hljs-comment">//check if there are values      let nextUp = this._storage[++this._start];      delete this._storage[this._start];      return nextUp;    }  }      size(){   return this._end - this._start;  }}</span>
</code></pre><pre><code><span class="hljs-keyword">let</span> microsoftQueue = <span class="hljs-keyword">new</span> Queue();
</code></pre><pre><code>microsoftQueue.enqueue(<span class="hljs-string">"{user: ILoveWindows@gmail.com}"</span>)microsoftQueue.enqueue(<span class="hljs-string">"{user: cortanaIsMyBestFriend@hotmail.com}"</span>)microsoftQueue.enqueue(<span class="hljs-string">"{user: InternetExplorer8Fan@outlook.com}"</span>)microsoftQueue.enqueue(<span class="hljs-string">"{user: IThrowApplesOutMyWindow@yahoo.com}"</span>)
</code></pre><pre><code><span class="hljs-comment">//Function to send everyone their Surface Studio!let sendSurface = recepient =&gt; {   sendTo(recepient);}</span>
</code></pre><pre><code><span class="hljs-comment">//When your server is ready to handle this queue, execute this:</span>
</code></pre><pre><code><span class="hljs-keyword">while</span>(microsoftQueue.size() &gt; <span class="hljs-number">0</span>){  sendSurface(microsoftQueue.dequeue());}
</code></pre><p>And there it is folks! Everyone who was waiting in the microsoftQueue now gets their awesome new Surface Studio thanks to you.</p>
<p>To be thorough, there are definitely some quick optimizations that can make code work more logically.</p>
<ol>
<li>You can reset your start and end values to 0 once everyone in the queue has been served. It’s unlikely that your queue would ever hit the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER">“max” JavaScript number</a>, but it’s better to be safe than sorry.</li>
<li>You can switch out the “ end &gt; start check ” with the size method, thanks to 0 being evaluated as “false” due to JavaScript type coercion. Read all about <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Falsy">it h</a>ere.</li>
</ol>
<pre><code>dequeue(){    <span class="hljs-keyword">if</span>(<span class="hljs-built_in">this</span>.size()){ <span class="hljs-comment">//0 is a falsey value...coerced to return false      let nextUp = this._storage[++this._start];      delete this._storage[this._start];</span>
</code></pre><pre><code>      <span class="hljs-keyword">if</span>(!<span class="hljs-built_in">this</span>.size()){ <span class="hljs-comment">//Recheck after incrementing (!0 == true)        this._start = -1;        this._end = -1;       }            return nextUp;    }}</span>
</code></pre><p>And there you go, you’ve finished writing your basic Queue!</p>
<h3 id="heading-a-time-complexity-analysishttpbigocheatsheetcom-on-the-queue-methods">A <a target="_blank" href="http://bigocheatsheet.com/">time complexity analysis</a> on the queue methods</h3>
<p>Here’s the code again:</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Queue</span></span>{  <span class="hljs-keyword">constructor</span>(){    <span class="hljs-built_in">this</span>._storage = {};    <span class="hljs-built_in">this</span>._start = <span class="hljs-number">-1</span>; <span class="hljs-comment">//replicating 0 index used for arrays    this._end = -1; //replicating 0 index used for arrays  }    enqueue(val){    this._storage[++this._end] = val;   }</span>
</code></pre><pre><code>  dequeue(){    <span class="hljs-keyword">if</span>(<span class="hljs-built_in">this</span>.size()){ /      <span class="hljs-keyword">let</span> nextUp = <span class="hljs-built_in">this</span>._storage[++<span class="hljs-built_in">this</span>._start];      <span class="hljs-keyword">delete</span> <span class="hljs-built_in">this</span>._storage[<span class="hljs-built_in">this</span>._start];
</code></pre><pre><code>      <span class="hljs-keyword">if</span>(!<span class="hljs-built_in">this</span>.size()){         <span class="hljs-built_in">this</span>._start = <span class="hljs-number">-1</span>;        <span class="hljs-built_in">this</span>._end = <span class="hljs-number">-1</span>;       }            <span class="hljs-keyword">return</span> nextUp;    }  }    size(){   <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>._end - <span class="hljs-built_in">this</span>._start;  }}
</code></pre><p>The same logic for stacks also applies here:</p>
<p><strong>Enqueue</strong> (addition) is <strong>O(1)</strong>. Since you’ll always know where the end of the queue is (thanks to your end variable), you don’t have to iterate to add an item.</p>
<p><strong>Dequeue</strong> (removal) is <strong>O(1)</strong>. No iteration is necessary for removal since you always have the current start position.</p>
<p><strong>Size</strong> is <strong>O(1)</strong>. The size is always known thanks to your start and end variables.</p>
<p>One really important thing to note here is that queues aren’t meant to be infinite, although our queue class and JavaScript array will allow you to keep on adding items until the system runs out of memory.</p>
<p>One way to optimize is by making a space-limited array to create a circular queue. Damian Gordon provides a really good <a target="_blank" href="https://www.youtube.com/watch?v=ia__kyuwGag">video walk-through</a> on YouTube. This will also be handy for when we get to hash tables in future articles!</p>
<h3 id="heading-time-for-a-quick-recap">Time for a quick recap</h3>
<p>Queues:</p>
<ol>
<li>Follow a First In First Out (FIFO) pattern</li>
<li>Have a start and end property to track the front and back of your queue</li>
<li>Have an enqueue (add) and dequeue (remove) method to manage the contents of your queue</li>
<li>Have a size property that allows you to track how large your queue is</li>
</ol>
<h3 id="heading-heres-a-quick-challenge"><strong>Here’s a quick challenge</strong></h3>
<p>Using what you now know about Stacks and what you learned today about Queues, try re-implementing a Queue using just stacks.</p>
<p>As a quick hint, you’ll only need two stacks.</p>
<p>Thanks to Jason Holtkamp for coming up with this quick challenge!</p>
<h3 id="heading-further-reading"><strong>Further reading</strong></h3>
<p><a target="_blank" href="https://en.wikipedia.org/wiki/Queue_(abstract_data_type)">Wikipedia</a> as always ?</p>
<p><a target="_blank" href="https://en.wikipedia.org/wiki/Priority_queue">This Wikipedia article</a> on priority queue. We’ll come back to this in future articles.</p>
<p>A nice <a target="_blank" href="https://www.khanacademy.org/computer-programming/queue-structure/6427851233820672">demo</a> by Larry Serflaten on Khan Academy, where he uses push and pull in place of enqueue and dequeue.</p>
<p>And here’s the <a target="_blank" href="http://stackoverflow.com/questions/69192/how-to-implement-a-queue-using-two-stacks">Answer</a> for the quick challenge. Only look at this after trying it out for a bit yourself. You can also check out <a target="_blank" href="http://stackoverflow.com/users/3128926/levent-divilioglu">Levent Divilioglu</a>’s answer for a fantastic graphical representation.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
