Data Structures: Stacks And Queues I
Tags: javascript, webdev, beginners, computerscience
Published: 2022-02-28 10:36:12

This post is divided into 2 parts to make it easier for us to understand stacks and queues and how to use them. In this first part of the series, we'll be focused on functionality and use cases, while in the [next part](https://dev.to/m13ha/data-structures-stacks-and-queues-ii-41b6) we'll look at code implementation (Javascript); So let's get into it.  

<p>&nbsp;</p>

## Data Structures  

<p>&nbsp;</p>

![dive rewind](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f2nuhdct8guia0xpjum0.gif 
)

<p>&nbsp;</p>
  
Before we dive into things, let's take a step back and try to understand what data structures are and why they are useful.

<p>&nbsp;</p>

Data Structures are simply systems through which data is organized and stored, to enable easy access to said data. An example of a non-digital data structure is a dictionary. A dictionary contains words and their meanings, and these words are arranged alphabetically for easier access. The data in this context are the words and their definitions when this Pair is arranged to enable easy searching and reading; that's a data structure. 

<p>&nbsp;</p>


![Fast Data Image Use Data Structures](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sx35g6xu3yoslj0jw80h.jpg)

<p>&nbsp;</p>

Computers use data structures to store data to make it easier for us to access and use it; some examples of computer data structures are arrays, linked lists, trees, stacks, queues, hash tables, etc.

<p>&nbsp;</p>


## Types Of Data Structures

Data structures are divided into 2 main types Linear and Non-linear. Linear data structures have their data organized in a straightforward manner, with each element following the previous and connecting to the next. Examples of linear data structures include arrays, stacks, queues, Linked Lists, etc.

Non-linear data structures on the other hand store their data in a hierarchy with branches and levels. Examples include trees and graphs.

Data structures are also categorized into static and dynamic data structures. Learn why [here](https://www.geeksforgeeks.org/static-data-structure-vs-dynamic-data-structure/#:~:text=Dynamic%20data%20structures%20are%20designed,structures%20in%20the%20run%20time.&text=Static%20Data%20structure%20has%20fixed,memory%20complexity%20of%20the%20code.)

<p>&nbsp;</p>

Now that we have a basic understanding of what data structures are, why they are useful, and how they are categorized; let's finally take that dive into visualizing stacks and queues.
<p>&nbsp;</p>


![Full dive](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6nm5a79ou7mm62exgcql.gif)

<p>&nbsp;</p>

## Stacks

Stack data structures are similar to stacks in real life. The most common analogy used to describe what a stack data structure looks like is a stack of plates. 

<p>&nbsp;</p>

![stack of plates](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uoitdi1mxxalv7j2wv69.jpg)

<p>&nbsp;</p>

In this analogy the plates represent data and the data can be anything; functions, strings, images etc. In order to take a plate from the stack we have to take it from the top, and when adding plates to the stack we add it from the top. This process of adding and removing from the stack is called push (add to stack) and pop (remove from stack). Stacks operate on what is called a LIFO (Last In First Out) approach. The Top/Head of the stack is always the newest element.

<p>&nbsp;</p>


![Stack functionality image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5q9wjuuayz6cpf4rozsl.png)

<p>&nbsp;</p>

stacks also have methods like peek and isEmpty; the peek method shows the current top element of the stack and the isEmpty method returns true or false if the stack has an element inside or not.

<p>&nbsp;</p>

### Use Cases

Stacks are used in many algorithms and are present in browsers, operating systems, and games.

#### Javascript Call Stack

Javascript has a stack built into it to manage functions called the Call Stack. In Javascript you can write functions that call other functions and have those functions call other functions, and on and on and on. This is a problem though, because Javascript is a [single-thread](https://thecodest.co/blog/asynchronous-and-single-threaded-javascript-meet-the-event-loop/) language meaning it can only do one thing at a time, the call stack solves this problem by acting as a sort of to-do list keeping track of functions and the order they are called. Let's use this bread-making function as an example;

<p>&nbsp;</p>


![Call Stack Functionality](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t2jn0dczwe1c6uv33az4.png)


<p>&nbsp;</p>

when makeBread is invoked it is pushed to the call stack; getIngredients is then called inside the makeBread function, which in turn calls the goToStore function. As we know, the Javascript engine can only do [one thing at a time](https://www.geeksforgeeks.org/synchronous-and-asynchronous-in-javascript/#:~:text=Synchronous%20JavaScript%3A%20As%20the%20name,earlier%20statement%20to%20get%20executed.) so whenever a new function is called, Javascript pushes that function to the call stack and starts executing that function immediately. The call stack helps the Javascript engine to keep track of previous functions and pick up where it left off. Once a function is resolved it is popped from the stack.

<p>&nbsp;</p>

#### Undo/Redo Function

Stack data structure is used in undo and redo typing functions. Stacks help keep track of when new words are added and when words are deleted, which can be reversed using the redo or undo functions.

<p>&nbsp;</p>


## Queues

Queue data structures have a similar structure to stacks but operate differently, just like queues in real life use a FIFO (First In First Out) approach, so do queue data structures. Unlike stacks where the adding (pushing) and removing (popping) of elements occurs at the top/head of the stack, queues add (enqueue) their elements to the end of the queue and remove (dequeue) from the top/head.

<p>&nbsp;</p>


![Queue Functionality](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4jepu5q5yfp3j1hpgon9.png)


<p>&nbsp;</p>

Just like stacks, queues also have the peek and isEmpty methods and do the same thing as mentioned above.

<p>&nbsp;</p>

### Use Cases

Queues are best used in situations where the order in which the data is received is important. Some known applications of queues are in the Javascript Event Loop, printer sharing, FIFO schedules, Mail Queues, etc.

#### Javascript Task Queue

When a page is loaded in a browser, or a user clicks a button, the mouse is moved, a key is pressed on the keyboard, etc; These are all events in Javascript. Events occur when the browser or user interacts with the webpage.

Javascript script has queues built into it, one of which is the Task/Callback/Event Queue. Remember our bread-making function from before; let's imagine we attach that function to a button with a click event and let's make a function to make pizza and attach it to a button with a click event too. I want 2 loaves of bread and 2 pizzas so I click the make bread button twice and the make pizza button twice, but as we know Javascript can only do one thing at a time, so it needs a way to keep track of the click events and the order in which they happen, that's where the Task Queue comes into play.

<p>&nbsp;</p>

After the first click the call stack will be busy carrying out the function; all other clicks will be pushed (enqueued) into the Task Queue to wait for the Call Stack to be free. When the call stack is free, the oldest queued task is removed (dequeued) and pushed into the call stack and the cycle continues till both the Call Stack and Task Queue are empty; We can see this in action below.

<p>&nbsp;</p>

![event loop](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z5z867zisiptoee0zubq.gif)

<p>&nbsp;</p>

This cycle of queuing and dequeuing events from the Task Queue and pushing them into the Call Stack is part of a process in Javascript called the [Event Loop](https://youtu.be/8aGhZQkoFbQ).

<p>&nbsp;</p>

####CPU Scheduling (FCFS)

Queues are also used in CPU Scheduling; In situations where memory is limited processes need to be scheduled to ensure they are completed as fast as possible. One of the simplest scheduling algorithms to implement is the FCFS (first come, first served) Scheduling Algorithm, which is basically a queue that stores the processes in the order they arrive.


###Summary

So to summarize Stacks and Queues are Linear data structures that can be used in different ways to solve problems with data handling and management. We learned that Stacks operate using a LIFO (Last In First Out) principle while Queues use a FIFO (First In First Out). We used the Javascript Call Stack and Javascript Task Queue to understand how stacks and queues can be used to manage functions and events. Next time we'll look at how to implement Stacks and Queues in Javascript.

<p>&nbsp;</p>

[**Part 2**](https://dev.to/m13ha/data-structures-stacks-and-queues-ii-41b6)


![See you Later](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/weu5gmn430y07kuhqgxr.gif)

<p>&nbsp;</p>