已知栈的压入顺序,判断弹出顺序是否正确。
思路:
1、建立一个辅助栈
2、如果栈顶元素不等于弹出元素,则按顺序将压入序列的元素压入栈,直至栈顶元素等于弹出元素。(栈为空时的特殊操作)
3、弹出栈顶元素,更新弹出元素。
4、重复执行2、3直至,待处理的弹出序列为空。
#include<iostream>
#include<stack>
#include<vector>
using namespace std;
bool check(const vector<int> &a, const vector<int> &b)
{
stack<int> sta;
int len1 = a.size();
int len2 = b.size();
if (len2 == 0) return true;
if (len1 == 0) return false;
int aindex = 0;
int bindex = 0;
while (bindex < len2)
{
if (sta.size() == 0)
{
sta.push(a[aindex]);
aindex++;
}
while (aindex < len1)
{
if (sta.top() != b[bindex])
{
sta.push(a[aindex]);
aindex++;
}
else
{
break;
}
}
if (sta.top() != b[bindex]) return false;
sta.pop();
bindex++;
}
return true;
}
int main()
{
vector<int> a = { 1, 2, 3, 4, 5 };
vector<int> b = { 4, 5, 3, 2, 1 };
vector<int> c = { 4, 3, 5, 1, 2 };
cout << check(a, b);
system("pause");
return 0;
}