DEV Community

Purity Chepkurui
Purity Chepkurui

Posted on • Edited on

JavaScript Data Structures: Stacks

Alt Text

What is a stack

A stack is a list of elements only accessible from one end: the top. It is called a LIFO(Last in first out) data structure. Any element not currently at the top of the stack cannot be accessed. To get to an element at the bottom of the stack, all the elements above it must be disposed.

Creating a stack

First we will define the stack class and the constructor. The items array will store the elements of the stack.


class Stack {
    constructor(){
        this.items=[];
    }
};

Enter fullscreen mode Exit fullscreen mode

Next we will define the push() method. This add a new item or items to the top of the stack.


 push=(element)=>{
        return this.items.push(element);
    }
Enter fullscreen mode Exit fullscreen mode

To check the element at the top of the stack, we will define the peek() method.


 peek=(element)=>{
        return this.items[this.items.length - 1];
    }
Enter fullscreen mode Exit fullscreen mode

The pop() function removes and returns the top element from the stack.


pop=()=>{
        return this.items.pop();
    };
Enter fullscreen mode Exit fullscreen mode

To find how many element are in the stack, we define the size() functions


 size=()=>{
        return this.items.length;
    }
Enter fullscreen mode Exit fullscreen mode

To remove all elements in the stack we define the clear() functions


 clear=()=>{
        return this.items=[];
    }
Enter fullscreen mode Exit fullscreen mode

This is the full code of the Stack class


class Stack {
    constructor(){
        this.items=[];
    }
    push=(element)=>{
        return this.items.push(element);
    }
    peek=(element)=>{
        return this.items[this.items.length - 1];
    }
    pop=()=>{
        return this.items.pop();
    }
    size=()=>{
        return this.items.length;
    }
    clear=()=>{
        return this.items=[];
    }
}
Enter fullscreen mode Exit fullscreen mode

To use the Stack class:


let newStack= new Stack();
//to pop
newStack.pop();
//to add
newStack.push(3);
Enter fullscreen mode Exit fullscreen mode

Use cases of stacks

  1. Palindromes- palindromes are words that are spelled the same way forward as backwards like car, racecar. Stacks can be used to determine if a given word is a palindrome. The original string is pushed onto a stack moving from left to right. When the end of the string is reached, the stack contains the word in reverse order with the top of the stack being the first character and the bottom of the stack being the last letter. The reversed string is compared with the original string; if they are equal then the word is a palindrome.

  2. Multiple base conversions – Stacks can be used to convert a number from one base to another.

Top comments (0)