Stacks and Queues

With JavaScript

Objectives

At the end of this lesson you should be able to

  • explain what a stack is
  • explain what a queue is
  • create a stack with javascript
  • create a queue with javascript

What is a stack?

 

  • A stack is a basic data structure that can be logically thought as linear structure represented by a real physical stack or pile, a structure where insertion and deletion of items takes place at one end called top of the stack.
  • The basic concept can be illustrated by thinking of your data set as a stack of plates or books where you can only take the top item off the stack in order to remove things from it.
  • This structure is used all throughout programming. (hint: it is used a lot in searches like DFS and BFS)

Warning, wall of text!!!

Lets Play a Game!

Stacks are hard, lets play a game instead

https://www.mathsisfun.com/games/towerofhanoi.html

In your own words

what is a stack? And how would you use it?

Lets start building a stack

Create a constructor for a stack with the following method

  • push - Adds an item onto the stack

Your turn

Add the following methods to the constructor

  • top - Returns the most recently added item from the stack
  • pop - Removes the most recently added item from the stack

Stretch goals

  • isEmpty - True is no items are in the stack 
  • getSize - Returns the size of the stack

What is a Queue?

  • A queue is a basic data structure that is used throughout programming.
  • You can think of it as a line in a grocery store. The first one in the line is the first one to be served.

Your turn

Create a queue now with the following methods

  • enqueue - Add an item to the end of the queue
  • front - Return the item at the front of the queue
  • dequeue - Remove the item from the front of the queue

Stretch goals

  • isEmpty - True is no items are in the stack 
  • getSize - Returns the size of the stack

Questions

stacks and queues with js

By Brooks Patton

stacks and queues with js

Lets explore stacks and queues with javascript

  • 1,240