找出入栈序列与弹出序列的规律:
栈的栈顶元素与弹出序列按照顺序指定元素进行比较,如果不相等,则继续入栈,直至有这个元素或者当元素全部入栈结束入栈,如果当栈顶元素不等于按顺序指定的弹出序列的元素,那么该弹出序列即为错误,当栈顶元素与弹出序列都一一对应(栈空,弹出序列完结)即正确。
#include<iostream>
#include<stack>
bool isPopOrder(const int* pPush, const int* pPop, int nLength)
{
bool isPossible = false;
if (pPush != nullptr && pPop != nullptr && nLength > 0)
{
const int* pNextPush = pPush;
const int* pNextPop = pPop;
std::stack<int>m_stack;
while (pNextPop - pPop < nLength)//当弹出序列完结时,结束循环
{
while (m_stack.empty() || m_stack.top() != *pNextPop)//栈为空或者栈顶元素不等于弹出序列元素
{
if (pNextPush - pPush == nLength)//当弹入序列完结时,结束本循环
break;
m_stack.push(*pNextPush);
++pNextPush;
}
if (m_stack.top() != *pNextPop)//如果栈顶元素不等于弹出序列元素,直接结束循环
break;
m_stack.pop();//否则弹出
++pNextPop;
}
if (m_stack.empty() && pNextPop - pPop == nLength)//当栈为空以及弹出序列完结时表明弹出序列为可能的出栈顺序
isPossible = true;
}
return isPossible;
}
int main(int argc, char* argv[])
{
int pPush[5] = { 1,2,3,4,5 };
int pPop1[5] = { 4,5,3,2,1 };
int pPop2[5] = { 4,3,5,1,2 };
std::cout << isPopOrder(pPush, pPop1, 5) << std::endl;
std::cout << isPopOrder(pPush, pPop2, 5) << std::endl;
std::cin.get();
return 0;
}