Skip to content

使用数组实现栈

栈是一种后入先出的数据结构,我们只能查看和访问栈顶元素。

栈一般有以下方法:

  1. push(),添加元素到栈中(新添加的元素位于栈顶)。
  2. pop(),删除并返回栈顶元素。
  3. peek(),查看栈顶元素。
  4. size(),查看栈中元素个数。
  5. clear(),清空栈中所有元素。
  6. isEmpty(),如果栈中没有元素返回 true,否则返回 false

Code

javascript
// 创建一个基于数组的栈
class StackWithArray {
  #items = [];
  #cur = -1;
  // 移除所有的元素
  clear() {
    this.#items = [];
    this.#cur = -1;
  }
  // 放入元素到栈顶
  push(el) {
    this.#items[++this.#cur] = el;
  }
  // 弹出顶层元素
  pop() {
    if (this.#cur >= 0) {
      const el = this.#items[this.#cur];
      this.#items[this.#cur] = undefined;
      this.#cur--;
      return el;
    } else {
      return undefined;
    }
  }
  // 查看顶层元素
  peek() {
    return this.#items[this.#cur];
  }
  // 查看元素个数
  size() {
    return this.#items.length;
  }
  // 栈是否为空
  isEmpty() {
    return this.#cur === -1;
  }
}

Test Cases

javascript
const { StackWithArray } = require('./stack.cjs');

describe('StackWithArray', () => {
  it('isEmpty', () => {
    const stack = new StackWithArray();
    expect(stack.isEmpty()).toBe(true);
  });
  it('clear', () => {
    const stack = new StackWithArray();
    stack.push('A');
    stack.clear();
    expect(stack.isEmpty()).toBe(true);
  });
  it('push and peek', () => {
    const stack = new StackWithArray();
    stack.push('A');
    expect(stack.peek()).toBe('A');
    stack.push('B');
    stack.push('C');
    expect(stack.peek()).toBe('C');
  });
  it('push and pop', () => {
    const stack = new StackWithArray();
    stack.push('A');
    expect(stack.pop()).toBe('A');
    stack.push('B');
    stack.push('C');
    expect(stack.pop()).toBe('C');
    expect(stack.pop()).toBe('B');
  });
});