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

push, 添加元素到栈的顶端(末尾);
pop, 移除栈最顶端(末尾)的元素.

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

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

"栈"这个名称,可类比于一组物体的堆叠(一摞书,一摞盘子之类的)。

栈的 push 和 pop 操作的示意

 

复杂度

时间复杂度

获取:O(n)

查询:O(n)

插入:最好情况O(1) 最差情况O(n)

删除:最好情况O(1) 最差情况O(n)

空间复杂度

O(n)

代码实现

Stack.js

import LinkedList from '../linked-list/LinkedList';

export default class Stack {//栈类,栈其实就是只能在一端插入和删除的链表
  constructor() {
    // We're going to implement Stack based on LinkedList since these
    // structures are quite similar. Compare push/pop operations of the Stack
    // with prepend/deleteHead operations of LinkedList.
    this.linkedList = new LinkedList();//linkedList属性是一个链表对象
  }

  /**
   * @return {boolean}
   */
  isEmpty() {//判断是否是空栈
    // The stack is empty if its linked list doesn't have a head.
    return !this.linkedList.head;
  }

  /**
   * @return {*}
   */
  peek() {//获取栈的顶端的节点
    if (this.isEmpty()) {//如果空栈,返回null
      // If the linked list is empty then there is nothing to peek from.
      return null;
    }

    // Just read the value from the start of linked list without deleting it.
    return this.linkedList.head.value;//返回头结点的值
  }

  /**
   * @param {*} value
   */
  push(value) {//在顶端插入新节点
    // Pushing means to lay the value on top of the stack. Therefore let's just add
    // the new value at the start of the linked list.
    this.linkedList.prepend(value);
  }

  /**
   * @return {*}
   */
  pop() {//在顶端删除头结点,返回被删节点的值
    // Let's try to delete the first node (the head) from the linked list.
    // If there is no head (the linked list is empty) just return null.
    const removedHead = this.linkedList.deleteHead();
    return removedHead ? removedHead.value : null;
  }

  /**
   * @return {*[]}
   */
  toArray() {//返回所有栈元素的值组成的数组
    return this.linkedList
      .toArray()
      .map(linkedListNode => linkedListNode.value);
  }

  /**
   * @param {function} [callback]
   * @return {string}
   */
  toString(callback) {//返回所有节点调用节点自身的toString方法经由callback处理后的值组成的数组的字符串
    return this.linkedList.toString(callback);
  }
}

 

posted @ 2018-10-17 10:42  hahazexia  阅读(273)  评论(0)    收藏  举报