给定两个数组,数组A,数组B, A数组是压栈顺序,B数组是出栈顺序,判断B能否是A数组的出栈顺序。
举例:
数组A = {1,2,3,4,5};
数组B= {4,5,3,2,1}; 则B是A的出栈顺序
#include <iostream>
#include <stack>
using namespace std;
bool IsPopOrder(const int *A, const int* B, int Length)
{
if(A== NULL || B == NULL || Length <= 0)
{
return false;
}
stack<int> tmp;
int i = 0;
int j = 0;
for(i = 0; i < Length; i++)
{
tmp.push(A[i]);
if(tmp.top() == B[j])
{
while(!tmp.empty() && tmp.top() == B[j])
{
tmp.pop(); j++;
}
}
}
if(j == Length)
{
return true;
}
else
{
return false;
}
}
int main()
{
int A[] = {1,2,3,4,5};
int B[] = {4,5,3,2,1};
int C[] = {4,5,3,1,2};
cout<<IsPopOrder(A, B, 5)<<endl;
cout<<IsPopOrder(A, C, 5)<<endl;
system("pause");
return 0;
}