/************************************************************
题目:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二
个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如
序列1,2,3,4,5为某栈的压入顺序,则4,5,3,2,1是该栈对应的一个弹出
序列;而4,3,5,1,2,就不不可能是对应的弹出序列。
************************************************************/
#include<stdio.h>
#include<stack>
using namespace std;
/*
bool stackPushPopOrder(int* pushOrder, int* popOrder,int length)
{
if(!pushOrder || !popOrder || length<=0)
return false;
stack<int> intStack;
intStack.push(pushOrder[0]);
bool result = false;
int index = 1;
int i;
for(i=0; i<length; ++i)
{
for(int j = index; j<=length; ++j)
{
if(intStack.top() != popOrder[i] || intStack.empty())
{
if(j == 5) //如果所有数字都压入栈,仍没有找到相应弹出数字
return false;
intStack.push(pushOrder[j]);
++index;
}
else
{
intStack.pop();
break;
}
}
}
if(intStack.empty() && index==length && i==length)
return true;
else
return false;
}
*/
//对比一下书上的参考答案
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;
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 test1()
{
int pushOrder[5] = {1,2,3,4,5};
int popOrder[5] = {4,3,5,2,1};
if (IsPopOrder(pushOrder,popOrder,5))
{
printf("Yes!\n");
}
else
{
printf("No!\n");
}
}
void test2()
{
int pushOrder[5] = {1,2,3,4,5};
int popOrder[5] = {4,3,5,1,2};
if (IsPopOrder(pushOrder,popOrder,5))
{
printf("Yes!\n");
}
else
{
printf("No!\n");
}
}
int main()
{
test1();
test2();
return 0;
}
总结:如果下一个弹出的数字刚好是栈顶数字,那么直接弹出。如果下一个弹出的数字不在栈顶,我们把压栈序列中还没有入栈的数字压入辅助栈,知道把下一个需
要弹出的数字压入栈为止。如果所有的数字都压入了栈仍没有找到下一个弹出的数
字,那么该序列不可能是一个弹出的序列。
新的方法:
bool IsPopOrder(const int* arr1, const int* arr2, int length)
{
if(arr1 == NULL || arr2 == NULL || length <= 0)
return false;
stack<int> arr1Stack;
int i=0,j=0;
while(i<=length && j<=length) //防止第一个数组遍历到末尾就退出循环
{
if(arr1[i] == arr2[j])
{
++i;
++j;
}
else if(arr1Stack.empty() || arr1Stack.top() != arr2[j])
{
arr1Stack.push(arr1[i]);
++i;
}
else
{
arr1Stack.pop();
++j;
}
}
if(i>length && j>length)
return true;
else
{
return false;
}
}
==参考剑指OFFER