栈的push、pop序列 【微软面试100题 第二十九题】

题目要求:

  输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1、2、3、4、5是某栈的压栈序列,序列4、5、3、2、1是该压栈序列对应的一个弹出序列,单4、3、5、1、2就不可能是该压栈序列的弹出序列。

  参考资料:剑指offer第22题。

题目分析:

  如果下一个弹出的数字刚好是栈顶数字,那么直接弹出。如果下个弹出的数字不在栈顶,我们把压栈序列中还没有入栈的数字艳茹辅助栈,知道把下一个需要弹出的数字压入栈顶为止。如果所有的数字都压入了栈了仍然没有找到下一个弹出的数字,那么该序列不可能是一个弹出序列。

  下面通过下图来讲解一下具体过程:

代码实现:

// 《剑指Offer——名企面试官精讲典型编程题》代码
// 著作权所有者:何海涛

#include <iostream>
#include <stack>

using namespace std;

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;
}

// ====================测试代码====================
void Test(char* testName, const int* pPush, const int* pPop, int nLength, bool expected)
{
    if(testName != NULL)
        printf("%s begins: ", testName);

    if(IsPopOrder(pPush, pPop, nLength) == expected)
        printf("Passed.
");
    else
        printf("failed.
");
}

void Test1()
{
    const int nLength = 5;
    int push[nLength] = {1, 2, 3, 4, 5};
    int pop[nLength] = {4, 5, 3, 2, 1};
    
    Test("Test1", push, pop, nLength, true);
}

void Test2()
{
    const int nLength = 5;
    int push[nLength] = {1, 2, 3, 4, 5};
    int pop[nLength] = {4,3,5,1,2};
    
    Test("Test2", push, pop, nLength, false);
}

// push和pop序列只有一个数字
void Test5()
{
    const int nLength = 1;
    int push[nLength] = {1};
    int pop[nLength] = {2};

    Test("Test5", push, pop, nLength, false);
}

void Test6()
{
    const int nLength = 1;
    int push[nLength] = {1};
    int pop[nLength] = {1};

    Test("Test6", push, pop, nLength, true);
}

void Test7()
{
    Test("Test7", NULL, NULL, 0, false);
}
 
int main(void)
{
    Test1();
    Test2();
    Test5();
    Test6();
    Test7();

    return 0;
}
View Code
原文地址:https://www.cnblogs.com/tractorman/p/4063774.html