出栈入栈合法性检验
1.首先得讲一下对问题的理解,例如这样一道题问题如下:入栈的序列(1,2,3,4,5),出栈序列为(4,5,3,2,1)是合法序列,入栈的序列(1,2,3,4,5),出栈序列为(1,5,3,2,4)是不合法序列
2.问题就是这样,也就是说给我们一串这样的数组,我们用不同的入栈方式,是否能得到所要验证的出栈序列,那么我们可以还原入栈出战的场景,顺着出栈顺序的思路入栈出栈,看是否能够顺利出栈入栈(顺利出栈入栈即为,判断栈或者模拟栈最终为空);
3.画图理思路
代码:
#include<iostream>
#include<stack>
using namespace std;
bool push_pop_illegal(int* stack_in, int* stack_out, int in_size, int out_size);
void test_push_pop_illegal()
{
int stack_in[5] = { 1, 2, 3, 4, 5 };
int stack_out[5] = { 4, 5, 2, 3, 1 };
int in_size = sizeof(stack_in) / sizeof(stack_in[1]);
int out_size = sizeof(stack_out) / sizeof(stack_out[1]);
bool ret = push_pop_illegal(stack_in,stack_out,in_size,out_size);
if (ret)
cout << "合法" << endl;
else
cout << "不合法" << endl;
}
bool push_pop_illegal(int* stack_in, int* stack_out, int in_size, int out_size)
{
if (in_size != out_size)
return false;
else
{
stack<int> s;
int i = 0;
int j = 0;
for (i; i < in_size; i++)
{
s.push(stack_in[i]);
while (s.size() && s.top() == stack_out[j])
{
s.pop();
j++;
}
}
if (s.empty())
return true;
else
return false;
}
}