栈的压入、弹出(针对vector数组和队列不同 的使用方法)

针对vector和队列分别使用了2个代码,当然思想是一样的,但是操作起来有一点不太一样,其中vector不能使用pop_back,因为数组并没有delete,所以只能用遍历,但是队列可以只用用pop,所以这是二者之间最大的区别,如果题目没有要求,我建议用队列的方法,这样用起来比较方便,下面分别列举二者的代码:

vector数组版:

class Solution {
public:
    bool IsPopOrder(vector<int> pushV,vector<int> popV) {
        stack<int>temp_stack;      //定义一个临时栈,用来比较
        int k=pushV.size();
        if(k==0)return false;
        int j=0;
        for(int i=0;i<=k;i++)
        {
            temp_stack.push(pushV[i]);
            while(!temp_stack.empty()&&temp_stack.top()==popV[j])
            {
                temp_stack.pop();
                j++;               //有相同的就把栈弹出来,数组遍历下一个
            }
        }
        if(!temp_stack.empty()){
            return false;
        }
        else
            return true;
    }
};

队列版

class Solution {
public:
    bool IsPopOrder(queue<int> popV) {
        stack<int>temp_stack;      //定义一个临时栈,用来比较
        int k=pushV.size();
        if(k==0)return false;
        for(int i=1;i<=k;i++)
        {
            temp_stack.push(i);  //这个地方可以自己设置想要的数组,也可以作为参数传入
            while(!temp_stack.empty()&&temp_stack.top()==popV.front())
            {
                temp_stack.pop();
                popV.pop();             //有相同的就把栈弹出来,数组遍历下一个
            }
        }
        if(!temp_stack.empty()){
            return false;
        }
        else
            return true;
    }
};

最后,就是一定要看清楚题目,不然搞死你了

猜你喜欢

转载自blog.csdn.net/qq_36631272/article/details/82145865