Akhila Ariyachandra

Data Structures: Stack

Posted on 22nd April 2020

4 min read

0 views

Stack is a linear data structure where the elements follow a First In Last Out (FILO) order. It can also be thought as Last In First Out.

Stack Diagram

Stacks can be used for things like tracking which functions are currently running and the navigation state in a web app.

Implementing a Stack data structure

Even though we will be implementing the Stack data structure in TypeScript in this example, the basic concept can be implemented in any language.

First declare a class.

typescript

Then declare a private member variable array to store the data of the stack. Making it private will stop it from being directly accessed from outside the class.

typescript

Next, we need a way to check the size of the stack. We can use a getter to access the size of the _data array.

typescript

After that we’ll add a method to check whether the stack is empty or not.

typescript

Now we need a method to add new elements to the stack. We can use the push() method in arrays to add an element to the end of the _data array.

typescript

Finally we will implement two methods to check the element on top of the stack. One will just check the value, peek(), and the other will remove the element from the stack and return it, pop(). Both will throw an error if they are called when the stack is empty, i.e. the length of the _data array is zero.

typescript

Finally your stack class should look like this.

typescript

Below is an example on how to use the Stack class we just created. The stack can be created to hold any type of data.

typescript

If you enjoyed this post please leave a like or two below!!!

Check out my latest post...

Making delayed network requests in React after state changes

13th September 2021