首页 > 解决方案 > 从堆栈中弹出时出现分段错误

问题描述

任何人都可以帮助我找出此代码的错误吗?这是一个hackerrank问题MAXIMUM ELEMENT。对于案例 2,“maxes.pop()”行一直给我分段错误。注释掉该行实际上允许代码编译。

问题:

您有一个空序列,您将收到查询。每个查询都是以下三种类型之一:

1 x - 将元素 x 推入堆栈。
2 - 删除存在于堆栈顶部的元素。
3 - 打印堆栈中的最大元素。

功能说明

在下面的编辑器中完成 getMax 函数。

getMax 有以下参数:

退货

输入格式

输入的第一行包含一个整数, 。接下来的每一行都包含一个上面提到的查询。

约束

约束

所有查询均有效。

样本输入

STDIN   Function
-----   --------
10      operations[] size n = 10
1 97    operations = ['1 97', '2', '1 20', ....]
2
1 20
2
1 26
1 20
2
3
1 91
3

样本输出

26
91
    vector<int> getMax(vector<string> operations) {
    
    stack<int> nums;
    stack<int> maxes;
    vector<int> maxnums;
    int max = INT_MIN;
    //int top = -1;
    for(long unsigned int i=0; i<operations.size(); i++){
        switch(operations[i][0]){
        case('1'):
            cout<<"Operation 1"<<endl;
            nums.push(stoi(operations[i].substr(2)));
            if(nums.top() > max){
                max = nums.top();
                maxes.push(max);
            }
            break;
        
        case('2'):
            cout<<"Operation 2"<<endl;
            if(max==nums.top()){
                //cout<<"top element in maxes"<<maxes.top()<<endl;
                maxes.pop();
                max = maxes.top();
            }
            nums.pop();
            break;
        
        case('3'):
            cout<<"Operation 3"<<endl;
            maxnums.push_back(maxes.top());
            break;
        }
    }
    return maxnums;
}

标签: c++data-structuresstack

解决方案


考虑以下输入序列:

1 1 // push 1. Pushes 1 into nums and maxes
1 1 // push 1. Pushes 1 into nums, but not into maxes, since max = 1.
3   // delete top stack element
3   // delete top stack element

在处理第一3行之前,您的状态将是:

nums = {1, 1}
maxes = {1}
max = 1

现在,在第一次弹出时,一切都会好起来的,所以在第一次弹出后,您最终会得到以下状态:

nums = {1}
maxes = {}
max = 1

但是,在第二次弹出时,max == nums.top()仍然是正确的,因此您从maxes已经为空的堆栈中弹出。这就是为什么它会给你分段错误。


推荐阅读