techStackGuru

Stack Data Structure


Overview of the Stack Data Structure

In stacks, first elements added to the stack are removed first, following the Last-In-First-Out principle (LIFO).

stack-1

Skeleton of a stack class

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

  // The functions that need to be implemented
  // push(item)
  // pop()
  // peek()
  // isEmpty()
  // length()
} 

Stack data structure properties

  • Last-In-First-Out (LIFO): The stack is based on the Last-In-First-Out (LIFO) principle, which means the last element added will be the first element removed.
  • The stack is a dynamic data structure, meaning it can grow or shrink depending on the current programs requirements.
  • The stack is a linear data structure, which means it stores elements in a linear sequence. There is an addition or deletion of elements at one end of the sequence.
  • A stack has limited access to its elements. Since elements on top of the stack cannot be accessed without removing the elements on top, elements at the bottom of the stack cannot be accessed.
  • Stack pointers point to the top element of a stack, which is typically implemented using stack pointers. Each time elements are added to or removed from the stack, the stack pointer is updated.
  • Stack data structures operations

    Declaring

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

    Push

    An element is pushed to the top of the stack with this operation.

    push(element) 
    {  
      this.items.push(element); 
    }  

    Pop

    An element at the top of a stack is removed using this operation.

    pop() 
    {     
      this.items.pop(); 
    } 

    Peek

    In peek, the top element of a stack is returned without being removed.

    peek() 
    { 
      this.items[this.items.length - 1]; 
    } 

    IsEmpty

    Checks whether the stack is empty by using IsEmpty.

    isEmpty() 
    {    
      this.items.length == 0; 
    }

    There are many applications for stack data structures in computer science, including:

  • Function calls
  • Expression evaluation
  • Memory management
  • Backtracking
  • Undo/redo functionality
  • Example

    let stack = [];
    
    stack.push(1);
    console.log(stack); // [1]
    
    stack.push(2);
    console.log(stack); // [1,2]
    
    stack.push(3);
    console.log(stack); // [1,2,3]
    
    console.log(stack.pop()); // 3
    
    console.log(stack); // [1,2];
    
    //length
    console.log(stack.length) // 2
    
    //isEmpty
    console.log(stack.length == 0) // false