题目:输入两个整数序列,其中一个序列表示栈的push序列,判断另一个序列有没有可能是对应的pop序列。
思路:一直压栈,直至其top为pop序列的下标所指元素
于2012年7月17日凌晨所写:
#include <iostream>
#include <stack>
using namespace std;
int sourceArray[] = {1, 2, 3, 4, 5};
int destArray[] = {4, 5, 3, 2, 1};
const int sourceSize = sizeof sourceArray / sizeof *sourceArray;
const int destSize = sizeof destArray / sizeof *destArray;
bool isStackOrder(int *sourceArray, int *destArray, int sourceSize, int destSize)
{
bool result = false;
if (sourceArray == NULL || destArray == NULL || sourceSize <= 0 || destSize <= 0
|| sourceSize != destSize)
{
return result;
}
stack<int> istack;
int j = 0;
for (int i = 0; i < sourceSize; i++)
{
istack.push(sourceArray[i]);
if (istack.top() == destArray[j])
{
j++;
istack.pop();
}
}
while (j != destSize)
{
if (istack.top() != destArray[j])
{
result = false;
break;
}
else
{
j++;
istack.pop();
}
}
if (j == destSize && istack.empty())
{
result = true;
}
return result;
}
void main()
{
bool result = isStackOrder(sourceArray, destArray, sourceSize, destSize);
if (result == true)
{
cout << "is stack order" << endl;
}
else
{
cout << "not stack order" << endl;
}
}