/*******************************************************************
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;
}
剑指offer-栈的压入弹出序列判断
最新推荐文章于 2020-05-30 19:03:57 发布