1. Code implementation

class Stack {
    constructor() {
        this.list = [];
    }
    push(value) {
        this.list.push(value);
    }
    pop() {
        return this.list.pop();
    }
    peek() {
        return this.list[this.list.length - 1]}size() {
        return this.list.length;
    }
    isEmpty() {
        return this.list.length === 0;
    }
    clear() {
        this.list = [];
    }
    toString() {
        return this.list.join(",")}}Copy the code

2. Online code (including test code)

Code link

3. The complexity

  • Push: time and space complexity areO(1)
  • Out of the stack: time and space complexity areO(1)

4. The stack

  • Last in first Out (LIFO)
  • To put a ping-pong ball in a cup

5. Application scenarios

  • Function call stack
    • When multiple functions are called in a nested manner, the last function to be called is executed first, and the first function to be called is executed last
    • Example function call stack
  • The page stack
    • For example: first visit home page -> product details -> order settlement page; Return order: Order settlement page -> Product details -> home page

6. Related articles

  • Previous post: already the first
  • Implementing queues based on arrays

7. Corrections are welcome