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

C语言reverseStack函数Bug求助:栈反转失败,元素被首个元素替换

栈反转代码的Bug定位与修复

你代码的问题出在InsertAtBottom函数的递归调用参数上:

// 原错误代码行
ptr = InsertAtBottom(tempEle, ptr);

这里你错误地把临时弹出的tempEle传给了递归的InsertAtBottom,而不是一开始要插入底部的目标元素n。这会导致递归过程中反复把弹出的元素插回栈底,最终所有位置都被首个弹出的元素覆盖。

修正后的完整代码:

stack *InsertAtBottom(int n, stack *ptr)
{
    if (isEmpty(ptr))
    {
        push(n, ptr);
        return ptr;
    }
    int tempEle = peek(ptr);
    pop(ptr);
    // 修正:传入要插入的目标元素n,而非tempEle
    ptr = InsertAtBottom(n, ptr);
    push(tempEle, ptr);
    return ptr;
}

stack *ReverseStack(stack *ptr)
{
    if (!isEmpty(ptr))
    {
        int n =  peek(ptr);
        pop(ptr);
        ReverseStack(ptr);
        ptr = InsertAtBottom(n, ptr);
    }
    return ptr;
}

修复逻辑说明

  • InsertAtBottom的核心逻辑是:先弹出栈顶所有元素,直到栈为空时插入目标元素n,再把弹出的元素依次压回栈。
  • 原代码的错误导致递归时始终在插临时弹出的元素,而非最初的目标元素n,完全偏离了“把n插到栈底”的需求。
  • 修正后,递归调用传递的是最初的n,确保最终空栈时插入的是正确的目标元素,之后再把之前弹出的元素逐一压回,就能实现将n放到栈底的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 03:26:12