https://s3-us-west-2.amazonaws.com/secure.notion-static.com/4d563b0c-2716-448f-9f92-0f89d8c40574/stack-example.jpg

Stacks are very similar to arrays. We have a specific size (the number of elements in the stack). It is our stack's limit. And we're also going to need an index to iterate over our stack.

Remember all the software you have ever used that had a undo tool. That software (probably) used a stack for it.

When using a stack, in order to get a data that's somewhere in the middle, we'll need to remove all the elements placed on top of it. This is our stack, aka LIFO (Last In First Out). The software with the undo tool, that we've talked before, stores the previous states of your work using the LIFO method, so the last one appears first.

In summary, stack is a linear data structure that stores the element in a sequential manner.

Basic operations

Example

class MyStack {
  private stack: string[] = [];

  public push(value: string): void {
    this.stack.push(value);
  }

  public pop(): void {
    this.stack.pop();
  }

  public top(): string | undefined {
    return this.stack.length > 0 ? this.stack[this.stack.length - 1] : undefined;
  }

  public isEmpty(): boolean | undefined {
    return this.stack.length <= 0;
  }
}