zoukankan      html  css  js  c++  java
  • 剑指offer--面试题22

    关键在于思路,  需要两个输入向量,而函数中需要一个辅助栈

                    思路:以待判出栈序列为基础,逐个判断它与栈顶元素是否相等,相等则弹出且j++,这表明此元素可为出栈顺序元素,不相等则栈元素不断入栈,直至相等,否则则判为非出栈序列!

    #include<stack>
    
    bool IsStackSquence(int* array1, int length1, int* array2, int length2)
    {
        bool IsOutStack = true;
        if(array1 == NULL || length1 <= 0 || array2 == NULL || length2 <= 0 || length1 != length2)
            return !IsOutStack;
    
        std::stack<int> st;    
        int i = 0;
        int j = 0;
    
        st.push(array1[i++]);
    
        while(j < length2)
        {
            while(array2[j] != st.top() && i < length1)
            {
                st.push(array1[i]);
                i++;
            }
            if(array2[j] != st.top() && i == length1)
                return !IsOutStack;
    
            st.pop();
            j++;
        }
    
        return IsOutStack;
    }

     参考代码:

    #include <stack>
    
    bool IsPopOrder(const int* pPush, const int* pPop, int nLength)
    {
        bool bPossible = false;
    
        if(pPush != NULL && pPop != NULL && nLength > 0)
        {
            const int* pNextPush = pPush;
            const int* pNextPop = pPop;
    
            std::stack<int> stackData;
    
            while(pNextPop - pPop < nLength)
            {
                // 当辅助栈的栈顶元素不是要弹出的元素
                // 先压入一些数字入栈
                while(stackData.empty() || stackData.top() != *pNextPop)
                {
                    // 如果所有数字都压入辅助栈了,退出循环
                    if(pNextPush - pPush == nLength)
                        break;
    
                    stackData.push(*pNextPush);
    
                    pNextPush ++;
                }
    
                if(stackData.top() != *pNextPop)
                    break;
    
                stackData.pop();
                pNextPop ++;
            }
    
            if(stackData.empty() && pNextPop - pPop == nLength)
                bPossible = true;
        }
    
        return bPossible;
    }

    学习:const int*

    清醒时做事,糊涂时读书,大怒时睡觉,独处时思考; 做一个幸福的人,读书,旅行,努力工作,关心身体和心情,成为最好的自己 -- 共勉
  • 相关阅读:
    回答自己之前的提问!
    阅读《构建之法》第13-17章
    阅读《构建之发》10-12章
    阅读《构建之法 》8,9,10章
    Practise 5.2测试与封装(黑白盒
    Practice5.1 测试与封装5.1
    Practice4 阅读《构建之法》6-7章
    Practice3 阅读《构建之法》1-5章
    “做汉堡”之评价我的队友
    Practice2 结对子之“小学四则运算”
  • 原文地址:https://www.cnblogs.com/hello-yz/p/3271722.html
Copyright © 2011-2022 走看看