Data Structures: Stack
Posted on 22nd April 2020
4 min read•
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.
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.
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.
Next, we need a way to check the size of the stack. We can use a getter to access the size of the
After that we’ll add a method to check whether the stack is empty or not.
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
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.
Finally your stack class should look like this.
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.
Leave a Reaction below