题解 | #栈的压入、弹出序列#

栈的压入、弹出序列

https://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106

class Solution {
public:
    bool IsPopOrder(vector<int>& pushV, vector<int>& popV) {
        // 特殊情况
        if (pushV.size() == 0)
            return true;
        
        int idx_push = 0;
        int idx_pop = 0;
        int length = pushV.size();
        stack<int> temp;
        // 出栈入栈总共的操作数是元素个数的两倍
        for (int i = 0; i < length * 2; i++) {
            if (!temp.empty() && temp.top() == popV[idx_pop]) {
                temp.pop();
                idx_pop++;
            } else {
                temp.push(pushV[idx_push++]);
            }
        }

        return temp.empty();
    }
};

需要注意的是第14行如果写为:if (temp.top() == popV[idx_pop] && temp.empty())则会报错,因为编译器会先判断temp.top()是否与popV[idx_pop]相等,如果此时temp为空则会报错。所以要先进行是否为空的判断。

全部评论

相关推荐

头像
04-29 10:53
已编辑
东北大学 自动化类
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务