对于一个给定的入栈顺序,可能的出栈顺序会有很多,但是肯定都要遵循栈“后进先出”的特点,那么怎么进行合法性检测呢?
算法思想如下:
- 定义变量InIndex标记入栈序列的当前位置,定义OutIndex标记出栈序列的当前位置
- 对InIndex和Outindex处的数进行比较,如果相同,同时往后走。
- 如果不相同,则出栈序列去和辅助栈的栈顶的数据比较,如果相同,则pop掉栈顶,++OutIndex,然后继续和栈顶比较,如果相同,只要入栈队列没走完,就将数据放入辅助栈。
- 如果入栈序列已经走完了,让出栈序列依次栈顶数据比较,只要不匹配肯定是非法的。
图示如下:
基于这样的思想,可以写出如下代码:
#include<stack>
#include<vector>
using namespace std;
bool CheckStack(vector<int> In, vector<int> Out)
{
if (In.size() != Out.size())//判断入栈和出栈的个数是否相同
cout << "Input Error!\n" << endl;
stack<int> s;
size_t InIndex = 0;
size_t OutIndex = 0;
while (InIndex <= In.size() && OutIndex <= Out.size())
{
if (In[InIndex] == Out[OutIndex])//如果入栈等于出栈,继续往后比较
{
++InIndex;
++OutIndex;
}
else if (!s.empty() && Out[OutIndex] == s.top())//如果入栈和出栈不匹配,出栈序列就去和栈顶比
{
while (!s.empty() && Out[OutIndex] == s.top())
{
s.pop();
++OutIndex;
}
}
else//当前不匹配,入栈的序列继续往后走
{
//将不匹配的先入到栈中
s.push(In[InIndex]);
++InIndex;
}
if (InIndex >= In.size())//如果入栈序列已经走完,出栈序列和栈顶元素一一比较
{
while (!s.empty() && Out[OutIndex] == s.top())
{
s.pop();
++OutIndex;
}
//如果和栈中比较完,两个序列都走完了,即表明顺序合法
if (InIndex == In.size() && OutIndex == Out.size())
{
return true;
}
//说明出栈的序列中和栈顶有不匹配的数,即出栈顺序不合法
else
{
return false;
}
}
}
}
int main()
{
#if 0
vector<int> In = { 1, 2, 3, 4, 5 };
vector<int> Out = { 5, 4, 3, 2, 1 };
cout<<CheckStack(In, Out)<<endl;
#endif
#if 1
vector<int> In = { 1, 2, 3, 4, 5 };
vector<int> Out = { 3, 2, 1, 4, 5 };
cout << CheckStack(In, Out) << endl;
#endif
#if 0
vector<int> In = { 1, 2, 3, 4, 5 };
vector<int> Out = { 5, 4, 2, 3, 1 };
cout << CheckStack(In, Out) << endl;
#endif
system("pause");
return 0;
}
如有错误的地方,还望更正!