剑指offer-栈的压入弹出序列判断

/*******************************************************************
Copyright(c) 2016, Tyrone Li
All rights reserved.
*******************************************************************/
// 作者:TyroneLi
//

/*
Q:
    栈的压入和弹出序列:
        输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是不是
        该栈的弹出顺序。
S:
    如果下一个弹出的数字刚刚好是栈顶的数字,那么就直接弹出;如果下一个弹出的
    数字不在栈顶,那么就把压栈序列中还没有入栈的数字压入辅助栈中,知道下一个
    需要弹出的数字压入栈顶为止。如果所有的数字都压入栈中但是还没有找到下一个
    需要弹出的数字,那么该序列就不是一个弹出序列。
*/

#include <iostream>
#include <stack>
#include <cstdio>
#include <cstdlib>


bool isPreOrder(const int*mPush, const int*mPop, int length)
{
    bool result = false;

    if(mPush != nullptr && mPop != nullptr && length > 0)
    {
        const int*mPushNext = mPush;
        const int*mPopNext = mPop;

        std::stack<int> mStack;

        while((mPopNext - mPop) < length)
        {
            while(mStack.empty() || mStack.top() != (*mPopNext))
            {
                if((mPushNext - mPush) == length)
                    break;

                mStack.push((*mPushNext));
                mPushNext++;
            }

            if(mStack.top() != (*mPopNext))
                break;
            
            mStack.pop();
            mPopNext++;
        }

        if(mStack.empty() && (mPopNext - mPop) == length)
            result = true;
    }
    return result;
}

void test_1()
{
    int push[] = {1,2,3,4,5};
    int pop[] = {4,5,3,2,1};
    std::cout << isPreOrder(push, pop, 5) << std::endl;

    int pop_2[] = {4,5,3,1,2};
    std::cout << isPreOrder(push, pop_2, 5) << std::endl;

    int pop_3[] = {5,4,3,2,1};
    std::cout << isPreOrder(push, pop_3, 5) << std::endl;

    int*pop_4 = nullptr;
    std::cout << isPreOrder(push, pop_4, 5) << std::endl;
}

int main(int argc, char**argv)
{

    test_1();

    return 0;
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值