Ricardo Borges

Ricardo Borges

Personal blog

Data Structures in TypeScript - Stack

A stack uses LIFO (last-in-first-out) ordering, the most recent item added is the first item to be removed, just like a real stack. Some uses of this data structure are expressions evaluations and conversion (prefix, postfix, and infix), backtracking, and memory management.

stack

Representation

A stack can be implemented using an array or a linked list, can be either fixed or dynamic size.

Basic operations

  • Push - Add an item to the top of the stack
  • Pop - Remove the top item from the stack
  • Peek - Return the top of the stack, without removing it.
  • isEmpty - Return true if the stack is empty.
  • isFull - Return true if the stack is full, used when the stack is fixed size.

Here's an implementation of a stack using an array, in TypeScript an array doesn't have a fixed length, so the operation isFull is not required, however, you can implement a stack with a fixed length and use that operation.

1class Stack<T> {
2  private array: T[] = [];
3
4  pop(): T | undefined {
5    if (this.isEmpty()) throw new EmptyStackException();
6
7    return this.array.pop();
8  }
9
10  push(data: T): void {
11    this.array.push(data);
12  }
13
14  peek(): T {
15    if (this.isEmpty()) throw new EmptyStackException();
16
17    return this.array[this.array.length - 1];
18  }
19
20  isEmpty(): boolean {
21    return this.array.length === 0;
22  }
23}
github iconlinkedin icontwitter icon
Buy Me A Coffee