Does anyone could tell me why?


  • 0
    A

    The current could pass the test cases.
    My problem is that if I changed NestedInteger temp = record.top(); to NestedInteger &temp = record.top();
    runtime error appear, and it appears at record.top().add(temp); just next one line in the code.

    I have comment the problem lines in the code

    I know the problem is that after the top of the stack has been pop, the referenced data may be changed. But I haven't push any data in the stack, so I think it should be ok.
    Could anyone explain more for me?

        NestedInteger deserialize(string s) {
            int left =0, flag =1;
            stack<NestedInteger> record;
            record.push(NestedInteger());
            while(left < s.size()){
                if(s[left] == '['){
                    record.push(NestedInteger());
                    left++;
                }
                else if(s[left] == ']'){
                    NestedInteger temp = record.top();   
                //  NestedInteger& temp = record.top();    runtime error appear on record.top().add(temp);
                    record.pop();
                    record.top().add(temp);
                    left++;
                }
                else if(isdigit(s[left])){
                    int sum =0;
                    while(isdigit(s[left])){
                        sum *= 10;
                        sum += s[left]-'0';
                        left++;
                    }
                    sum *= flag;
                    record.top().add(NestedInteger(sum));
                    flag =1;
                }
                else if(s[left]=='-'){
                    flag =-1;
                    left++;
                }
                else
                    left++;
            }
            
            return record.top().getList().front();
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.