You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript栈最大值算法问题求助:全负数栈返回错误值

解决JavaScript栈最大值算法的全负数栈问题

问题根源

你的代码有三个致命问题:

  1. 初始值错误:count初始化为0,全负数栈里所有元素都比0小,导致count永远不会更新,最终返回0而非正确的最大负数。
  2. 循环逻辑作废:while(true)里直接return count加break,循环只跑一次,根本没遍历栈里的所有元素。
  3. 重复调用pop():判断和赋值时多次调用pop(),不仅跳过大量元素没检查,还直接把栈拆得乱七八糟。

修正后的实现(保持栈结构,推荐)

这个实现严格遵守只能用pop()、push()、peek()的要求,而且操作后栈的结构完全不变:

function maxValue(stack) {
    // 先通过peek判断栈是否为空
    if (stack.peek() === undefined) {
        return -Infinity;
    }

    let max = -Infinity;
    const tempStack = [];

    // 遍历栈中所有元素
    while (stack.peek() !== undefined) {
        const current = stack.pop();
        // 更新最大值
        if (current > max) {
            max = current;
        }
        // 把弹出的元素暂存到临时栈
        tempStack.push(current);
    }

    // 把临时栈里的元素推回原栈,恢复结构
    while (tempStack.length > 0) {
        stack.push(tempStack.pop());
    }

    return max;
}

简化版(不保持栈结构)

如果不需要保留原栈的内容,这个版本更简洁:

function maxValue(stack) {
    let max = -Infinity;
    let current;

    while ((current = stack.pop()) !== undefined) {
        if (current > max) {
            max = current;
        }
    }

    return max;
}

关键修正点

  • 把最大值初始值设为-Infinity,确保任何元素(包括负数)都能正确更新最大值。
  • 用peek()判断栈是否为空,避免提前弹出元素破坏栈结构。
  • 每个元素只调用一次pop(),保证所有元素都被检查到。
  • 临时栈的使用让原栈在操作后保持原样,符合数据结构的使用规范。

内容的提问来源于stack exchange,提问作者poopmachine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 09:46:04