Skip to content

LeetCode题解:155. 最小栈,使用链表代替栈,JavaScript,详细注释 #147

@chencl1986

Description

@chencl1986

原题链接:https://leetcode-cn.com/problems/min-stack/

解题思路:

参考了详细通俗的思路分析,多解法的第3种方法。建议先看该题解,再来看我的注释。

  1. 使用链表模拟栈,head节点始终为栈顶,入栈时创建一个新节点,同时存储入栈的值和最小值,再将新节点赋值给head。
  2. 出栈的时候只需要移动一次链表即可。
  3. 查看栈顶和最小值,只需返回head存储的值即可。
var MinStack = function () {
  // 创建链表
  this.Node = function Node(value, min) {
    this.value = value;
    this.min = min;
    this.next = null;
  };
  this.head = null;
};

/**
 * @param {number} x
 * @return {void}
 */
MinStack.prototype.push = function (x) {
  // 如果当前链表为空,则直接设置一个节点
  if (!this.head) {
    this.head = new this.Node(x, x);
  } else {
    // 创建一个新节点,作为栈顶,将其存储在head
    const newHead = new this.Node(x, Math.min(x, this.head.min));
    newHead.next = this.head;
    this.head = newHead;
  }
};

/**
 * @return {void}
 */
MinStack.prototype.pop = function () {
  // pop时直接将链表向前移动一个节点即可
  if (this.head) {
    this.head = this.head.next;
  }
};

/**
 * @return {number}
 */
MinStack.prototype.top = function () {
  // 查看栈顶时,返回head的值,head即为栈顶
  if (this.head) {
    return this.head.value;
  }
};

/**
 * @return {number}
 */
MinStack.prototype.getMin = function () {
  // 查看栈顶时,返回head存储的最小值,head即为栈顶
  if (this.head) {
    return this.head.min;
  }
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions