JavaScript - 栈

Telentjsjs算法小于 1 分钟

JavaScript - 栈

栈数据结构

创建一个基于数组的栈

class Stack {
  constructor() {
    this.count = 0;
    this.items = {};
  }
  // 添加元素
  push(element) {
    this.items[this.count] = element;
    this.count += 1;
  }
  // 移除元素
  pop(element) {
    if (this.isEmpty()) {
      return undefined;
    }
    this.count -= 1;
    const result = this.items[this.count];
    delete this.items[this.count];
    return result;
  }
  // 查看栈顶元素
  peek() {
    if (this.isEmpty()) {
      return undefined;
    }
    return this.items[this.count - 1];
  }
  // 检查栈是否为空
  isEmpty() {
    return this.count === 0;
  }
  // 栈长度
  size() {
    return this.count;
  }
  // 清空栈元素
  clear() {
    this.items = {};
    this.count = 0;
    /**
     * while(!this.isEmpty()) {
     *  this.pop()
     * }
     */
  }
  toString() {
    if (this.isEmpty()) {
      return "";
    }
    let objString = `${this.items[0]}`;
    for (let i = 1; i < this.count; i += 1) {
      objString = `${objString},${this.items[i]}`;
    }
    return objString;
  }
}
// 使用 Stack 类
const stack = new Stack();

保护数据结构内部元素

下划线命名约定

class Stack {
  constructor() {
    this._count = 0;
    this._items = {};
  }
}

Symbol

const _items = Symbol("stackItems");
class Stack {
  constructor() {
    this[_items] = [];
  }
}

WeakMap

const items = new WeakMap();
class Stack {
  constructor() {
    items.set(this, []);
  }
  push(element) {
    const s = items.get(this);
    s.push(element);
  }
  pop() {
    const s = items.get(this);
    const r = s.pop();
    return r;
  }
}
上次编辑于:
贡献者: 张振阳