简体   繁体   中英

Segmentation Fault when popping from a stack

Anyone can help me with finding out the error with this code? This is for a hackerrank question MAXIMUM ELEMENT. For the case 2, the line "maxes.pop()" keeps giving me segmentation fault. Commenting that line out actually allows the code to compile.

QUESTION:

You have an empty sequence, and you will be given queries. Each query is one of these three types:

1 x -Push the element x into the stack.
2 -Delete the element present at the top of the stack.
3 -Print the maximum element in the stack.

Function Description

Complete the getMax function in the editor below.

getMax has the following parameters:

  • string operations[n]: operations as strings

Returns

  • int[]: the answers to each type 3 query

Input Format

The first line of input contains an integer, . The next lines each contain an above mentioned query.

Constraints

Constraints

All queries are valid.

Sample Input

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

Sample Output

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;
}

Consider the following input sequence:

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

Before processing the first 3 line, your state will be this:

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

Now, on the first pop, everything will be fine, so after the first pop, you will end up with this state:

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

However, on on the second pop, max == nums.top() is still true, so you pop from your maxes stack, which is already empty. That is why it gives you the segmentation fault.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM