A Stack follows the Last-In-First-Out (LIFO) principle

January 28, 2024 2:57 PM

Data Structure implementation of a stack in JavaScript

A Stack is another type of data structure that follows the Last-In-First-Out (LIFO) principle. This means that the last element that is added to the stack will be the first one to be removed.

Think of it like a stack of plates. The last plate you put on the stack is the first one you would take off when you need a plate.

In terms of programming, a stack typically has the following operations:

  1. Push: This operation adds an element to the top of the stack.

  2. Pop: This operation removes an element from the top of the stack.

  3. Peek/Top: This operation returns the top element of the stack without removing it.

  4. IsEmpty: This operation checks if the stack is empty.

Here's a simple implementation of a stack in JavaScript:

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

  // Add an element to the top of the stack
  push(element) {
    this.items.push(element);
  }

  // Remove an element from the top of the stack
  pop() {
    if (this.isEmpty()) return 'Underflow';
    return this.items.pop();
  }

  // Get the top element of the stack
  peek() {
    if (this.isEmpty()) return 'No elements in Stack';
    return this.items[this.items.length - 1];
  }

  // Check if the stack is empty
  isEmpty() {
    return this.items.length == 0;
  }
}

Comments


    Read next