DEV Community

Jack Cole
Jack Cole

Posted on • Updated on

Learning the Stack

A stack is a data structure in which we only have access to the most recently added element. To best understand the stack I like to picture a pile of cards. Whenever we add to the pile of cards, we place one on the top of the pile. Whenever we remove a card, it also must come from the top of the pile. If we want a card in the middle of the stack. We would need to keep on removing from the top of the stack until we get the desired card. This concept is known as FILO, or first in last out.

Stack example from wikipedia

As you noticed in the example image above. The main methods we will be using in a stack class are push and pop. With that in mind lets implement the stack class. Let's start with the constructor. We know we want to easily be able to add and remove the last element so an array is perfect.

Stack constructor

Javascript even provides us with push and pop methods for arrays. This makes implementing the push and pop methods incredibly easy.

Push and pop methods

But what if we were to try to use the pop method while the stack was empty? Let's add in some error handling.

Error Handling

Much better! Using a ternary we check to see if the stack is empty. If it is we return our error message, if it's not we pop off the top of the stack.

Some other common helper methods that could be added to a stack class are peek, where we look at the top element of the stack without removing it, is empty, where we check if the stack is empty, and a method that prints out the entirety of the current stack.

If you were looking for practice using a stack a perfect problem that can be solved by utilizing a stack is valid parentheses. Take a look at the problem and think about how a stack could be useful.

If you wanted to look at the code for this lesson the github link is here.

Top comments (1)

Collapse
 
wulymammoth profile image
David • Edited

Interesting post, Jack

I think it's worth noting that one can just use the dynamic array in JS as a stack: const stack = []. It's a tad bit odd to "re-wrap" its API in a class unless, of course, you'd like to provide custom errors or extend its interface with things like an Stack.prototype.empty method. I think creating a StackEmpty error that extends from Error and throwing it would be a nicer interface if the consumer of the stack needs to know when a stack is empty rather than returning a string masquerading as an error.

A couple of not so common interview related interview questions that may be good to know is how to implement a stack using queues and how to implement queues using only stacks and how to implement queues with only linked lists