【问题标题】:Segmentation Fault when popping from a stack从堆栈中弹出时出现分段错误
【发布时间】:2021-08-05 07:48:52
【问题描述】:

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

问题:

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

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

功能说明

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

getMax 有以下参数:

  • 字符串操作[n]:字符串操作

返回

  • int[]:每个类型 3 查询的答案

输入格式

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

约束

约束

所有查询均有效。

示例输入

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-structures stack


    【解决方案1】:

    考虑以下输入序列:

    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 堆栈中弹出。这就是为什么它会给你分段错误。

    【讨论】:

      猜你喜欢
      • 2019-09-30
      • 2013-04-16
      • 2014-11-30
      • 2021-01-17
      • 2021-12-03
      • 2015-02-14
      • 2011-10-30
      • 1970-01-01
      相关资源
      最近更新 更多