3 mins read


Stack

Explore the ins and outs of stack data structures in our latest blog post. From understanding the fundamentals to advanced techniques, discover how to leverage stacks for optimal efficiency in your coding projects.


Introduction

A stack is a fundamental data structure in computer science that follows the Last-In-First-Out (LIFO) principle. In a stack, elements are added and removed from the top only, resembling a stack of plates where you can only add or remove the top plate. This characteristic makes it particularly useful for tasks where the order of operations matters, such as function calls, expression evaluation, and backtracking algorithms.

Available Operations

  1. Push: Adding an element to the top of the stack.
  2. Pop: Removing the element from the top of the stack.
  3. Peek (or Top): Viewing the element at the top of the stack without removing it.
  4. IsEmpty: Checking if the stack is empty.
  5. IsFull (in bounded stacks): Checking if the stack has reached its maximum capacity.

Implementation

// Define a generic class for the stack
class Stack<T> {
    private items: T[]; // Array to store the stack elements
 
    constructor() {
        this.items = []; // Initialize the stack as an empty array
    }
 
    // Push element onto the stack
    push(element: T): void {
        this.items.push(element); // Add element to the end of the array
    }
 
    // Remove and return the top element from the stack
    pop(): T | undefined {
        return this.items.pop(); // Remove and return the last element of the array
    }
 
    // Return the top element of the stack without removing it
    peek(): T | undefined {
        return this.items[this.items.length - 1]; // Return the last element of the array
    }
 
    // Check if the stack is empty
    isEmpty(): boolean {
        return this.items.length === 0; // If the length of the array is 0, stack is empty
    }
 
    // Return the number of elements in the stack
    size(): number {
        return this.items.length; // Return the length of the array
    }
 
    // Clear the stack
    clear(): void {
        this.items = []; // Clear the array by assigning it to an empty array
    }
}

Usage

const stack = new Stack<number>(); // Create a stack of numbers
stack.push(1);
stack.push(2);
stack.push(3);
 
console.log("Stack size:", stack.size()); // Output: 3
console.log("Top element:", stack.peek()); // Output: 3
 
console.log("Pop:", stack.pop()); // Output: 3
console.log("Stack size after pop:", stack.size()); // Output: 2
 
console.log("Is stack empty?", stack.isEmpty()); // Output: false
 
stack.clear();
console.log("Is stack empty after clearing?", stack.isEmpty()); // Output: true