题目:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。
假设压入栈的所有数字均不相等,例如压栈序列:1、2、3、4、5。序列:4、5、3、2、1是该栈序列对应的一个弹出序列。
//思路:知彼知己方能百战不胜,哈哈。 我们现在判断栈的弹出顺序是否合法,那我们就必须掌握到栈的基本特性:后进先出,(每次弹出栈的栈顶),
//那我们知道了栈顶,根据压栈顺序,我们就能确定当前栈中元素摆放位置,在根据弹出,最后确定当前栈是否为空,为空,说明出栈顺序正确,否则,错误。
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 = pPush;
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;
}