欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

元素出栈、入栈顺序的合法性

程序员文章站 2024-03-18 12:38:46
...
//元素出栈、入栈顺序的合法性。
#include<iostream>
#include<vector>
#include<stack>
using namespace std;
bool IsPopOrder(vector<int> push,vector<int> pop)
{
    if (push.size() != pop.size() || pop.size() == 0)
        return false;
    int len = push.size();
    int idx = 0;
    stack<int> s;//辅助栈
    for (int i = 0; i < len ; i++)
    {
        s.push(push[i]);//push序列依次入栈
        while (idx < len && s.size() > 0 && s.top() == pop[idx])//当pop序列中的元素与辅助栈中的元素相同时pop();
        {
            s.pop();
            idx++;
        }
    }
    if (s.size() == 0)//如果辅助栈为空,则说明依次按照pop序列pop()了数据,即出栈顺序合法
        return true;
    return false;
}
int main()
{
    vector<int> v1 = { 1,2,3,4,5 };
    vector<int> v2 = { 4,5,3,2,1 };
    cout << IsPopOrder(v1,v2) << endl;
    system("pause");
    return 0;
}