Sobes.tech
Junior — Middle

Can you explain what a Stack data structure is and how it works?

sobes.tech AI

Answer from AI

The Stack data structure is a collection of elements that operates on the LIFO (Last In, First Out) principle, meaning the last added element is the first to be removed.

Main operations of a stack:

  • push — add an element to the top of the stack;
  • pop — remove and return the top element;
  • peek (top) — view the top element without removing it;
  • isEmpty — check if the stack is empty.

Example of a stack implementation in JavaScript (Node.js):

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

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

  pop() {
    if (this.isEmpty()) {
      return null;
    }
    return this.items.pop();
  }

  peek() {
    if (this.isEmpty()) {
      return null;
    }
    return this.items[this.items.length - 1];
  }

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

// Usage:
const stack = new Stack();
stack.push(1);
stack.push(2);
console.log(stack.pop()); // 2
console.log(stack.peek()); // 1

Stacks are widely used in algorithms, for example, for graph traversal, function call implementation, undo actions, etc.

Can you explain what a Stack data structure is and… - sobes.tech