面试题31:栈的压入、弹出序列

栈的压入、弹出序列,很经典。

C++版本

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

// 定义辅助栈
stack<int> stack1;

bool IsPopOrder(vector<int> pushV, vector<int> popV){
    bool isPopOrder = false;
    int pushLength = pushV.size();
    int popLength = popV.size();

    if(pushLength > 0 && popLength > 0 && (pushLength == popLength)){
        isPopOrder = true;
        // 定义标记数组
        bool vis[pushLength];
        memset(vis, false, sizeof(vis));

        for(int i = 0; i < popLength; i++){
            // 下一个弹出的数字
            int popValue = popV[i];
            // 如果下一个弹出的数字刚好是栈顶数字,直接弹出
            if(stack1.size() > 0 && stack1.top() == popValue){
                stack1.pop();
            }

            // 如果下一个弹出的数字不在栈顶,则把压栈序列中还没有入栈的数字压入辅助栈
            else if(stack1.size() == 0 || stack1.top() != popValue){
                // 定义在未入栈的序列中是否找到需要弹出的数字
                bool flag = false;
                for(int j = 0; j < pushLength; j++){
                    // 判断该值是否已入栈
                    if(!vis[j]){
                        stack1.push(pushV[j]);
                        vis[j] = true;
                        // 在未入栈的序列中找到了需要弹出的数字
                        if(pushV[j] == popValue){
                            // 出栈
                            stack1.pop();
                            flag = true;
                            break;
                        }
                    }
                }
                if(!flag){
                    cout<<"AAA"<<popValue<<endl;
                    isPopOrder = false;
                    break;
                }
            }
            vector<int> vec_stack;
            cout<<"**********************"<<endl;
            while(!stack1.empty()){
                vec_stack.push_back(stack1.top());
                cout<<stack1.top()<<endl;
                stack1.pop();
            }
            cout<<"**********************"<<endl;
            for(int k = vec_stack.size() - 1; k >= 0; k--){
                stack1.push(vec_stack[k]);
            }
        }
    }
    return isPopOrder;
}

int main()
{
    vector<int> pushV;
    pushV.push_back(1);
    pushV.push_back(2);
    pushV.push_back(3);
    pushV.push_back(4);
    pushV.push_back(5);
    vector<int> popV;
    popV.push_back(4);
    popV.push_back(5);
    popV.push_back(3);
    popV.push_back(2);
    popV.push_back(1);

    if(IsPopOrder(pushV, popV))
        cout<<"yes"<<endl;
    else
        cout<<"no."<<endl;
    return 0;
}
原文地址:https://www.cnblogs.com/flyingrun/p/13387554.html