#

# 定义

在计算机科学中,一个**栈(stack)**是一种抽象数据类型,用作表示元素的集合,具有两种主要操作:

  • Push,添加元素到栈的顶端(末尾)
  • Pop,移除栈最顶端(末尾)的元素

以上两种操作可以简单概括为"后进先出(LIFO = last in,first out)"。

此外,应有一个peek操作用于访问栈当前顶端(末尾)的元素。

# 代码实现

# Stack

import LinkedList from 'LinkedList';

export default class Stack {
  constructor() {
    this.linkedList = new LinkedList();
  }
  
  isEmpty() {
    return !this.linkedList.head;
  }
  
  peek() {
    if (this.isEmpty()) {
      return null;
    }
    
    return this.linkedList.head.value;
  }
  
  push(value) {
    this.linkedList.prepend(value);
  }
  
  pop() {
    const removedHead = this.linkedList.deleteHead();
    return removeHead ? removeHead.value : null;
  }
  
  toArray() {
    return this.linkedList.toArray().map((linkedListNode) => linkedListNode.value);
  }
  
  toString(callback) {
    return this.linkedList.toString(callback);
  }
}
最近更新时间: 2023/8/22 17:55:30