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

Next Greater Element算法代码出现段错误的原因排查及修复咨询

排查并修复下一个更大元素代码中的段错误问题

我帮你找到了导致段错误的核心原因,咱们一步步拆解来看:
当处理某个元素时,如果它比栈中所有剩余元素都大,while(!stk.empty() && stk.top() <= arr[i])这个循环会把栈里的元素全部弹出,此时栈stk变成空的,但你紧接着执行了resStack.push(stk.top())——空栈调用top()是未定义行为,直接触发了段错误。

修复方案

只需要在弹出完栈中小于当前元素的元素后,先判断栈是否为空:

  • 如果栈为空,说明当前元素右侧没有更大的元素,往resStack里push -1
  • 如果栈不为空,再push栈顶元素

修复后的完整代码

#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution {
public:
    //Function to find the next greater element for each element of the array.
    vector<long long> nextLargerElement(vector<long long> arr, int n){
        vector<long long> res;
        stack<long long> stk, resStack;
        for(int i=n-1; i>=0; i--){
            if(stk.empty()){
                resStack.push(-1);
                stk.push(arr[i]);
            }
            else{
                while(!stk.empty() && stk.top() <= arr[i])
                    stk.pop();
                // 关键修改:先判断栈是否为空再操作
                if(stk.empty()){
                    resStack.push(-1);
                }
                else{
                    resStack.push(stk.top());
                }
                stk.push(arr[i]);
            }
        }
        while(!resStack.empty()){
            res.push_back(resStack.top());
            resStack.pop();
        }
        return res;
    }
};
// { Driver Code Starts.
int main() {
    int t;
    cin>>t;
    while(t--) {
        int n;
        cin>>n;
        vector<long long> arr(n);
        for(int i=0;i<n;i++)
            cin>>arr[i];
        Solution obj;
        vector <long long> res = obj.nextLargerElement(arr, n);
        for (long long i : res)
            cout << i << " ";
        cout<<endl;
    }
    return 0;
}
// } Driver Code Ends

额外优化建议

其实你可以不用额外的resStack,直接从后往前填充结果数组,这样能节省一点空间,代码也更简洁:

vector<long long> nextLargerElement(vector<long long> arr, int n){
    vector<long long> res(n);
    stack<long long> stk;
    for(int i=n-1; i>=0; i--){
        while(!stk.empty() && stk.top() <= arr[i])
            stk.pop();
        res[i] = stk.empty() ? -1 : stk.top();
        stk.push(arr[i]);
    }
    return res;
}

这个版本直接把结果存在res数组的对应位置,避免了两次栈的中转操作,效率更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 17:04:08