栈的弹出压入序列(C++)

栈的弹出压入序列(C++)题目:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)

栈的弹出压入序列(C++)分析:以压入1,2,3,4,5,弹出4,5,3,2,1为例,首先压入与弹出序列用vector执行,接受需要stack(先进后出),每压入一个元素都需要与与弹出序列判等,如果相等直接pop(),否则继续压入,而判等条件s.top() == popV[j],判等次数需要一个循环while,退出条件就是压入的所有元素都弹出了,即s.empty(),最后return s.empty();如果为空,即弹出序列正确,不为空,则弹出序列错误
栈的弹出压入序列(C++)

#include<iostream>
using namespace std;
#include<vector>
#include<stack>

class Solution {
public:
    bool IsPopOrder(vector<int> pushV, vector<int> popV) {
        stack<int> s;
        int j = 0;
        for (int i = 0; i<pushV.size(); i++)
        {
            s.push(pushV[i]);
            while (!s.empty() && s.top() == popV[j])
            {
                s.pop();
                j++;
            }
        }
        return s.empty();
    }
};

int main()//测试
{
//用数组给vector提供测试用例
    /*int a[] = { 1, 2, 3, 4, 5 };
    vector<int> pushV(a, a + 5);
    int b[] = { 4, 5, 3, 2, 1 };
    vector<int> popV(b, b + 5);*/
//直接用vector容器
    vector<int> v1{ 1, 2, 3, 4, 5 };
    vector<int> v2{4,5,3,2,1};
    Solution S;
    if (S.IsPopOrder(v1, v2))
        cout <<  "True" << endl;
    else
        cout << "Flase" << endl;
    cout << "Hello world!" << endl;
    return 0;
}

猜你喜欢

转载自blog.51cto.com/14233078/2445125