// test14.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include<string>
#include<cctype>
#include <vector>
#include<exception>
#include <initializer_list>
using namespace std;
class Solution {
public:
bool IsPopOrder(vector<int> pushV, vector<int> popV) {
vector<int> temp;
int i = 3;
do {
if (pushV.empty() &&!temp.empty()&& *(temp.end() - 1) != *(popV.begin()))
break;
if ((!temp.empty()) && (*(temp.end() - 1) == *(popV.begin())))//如果temp的栈顶等于popV的栈尾
{
cout << "temp: " << *(temp.end() - 1) << endl;
temp.pop_back();//删除temp的栈顶
cout << "popV: " << *(popV.begin()) << endl;
popV.erase(popV.begin());//删除popV的栈尾
}
else if(!pushV.empty())
{
temp.push_back(*(pushV.begin()));
pushV.erase(pushV.begin());
}
} while ( !popV.empty());
if (!popV.empty())
{
// cout << "错误"<<endl;
return false;
}
else
{
// cout << "正确" << endl;
return true;
}
}
};
int main()
{
Solution so;
vector<int> pushV = { 1,2,3,4,5 };
vector<int> popV01 = { 4,5,3,2,1 };
vector<int> popV02 = { 4,3,5,1,2 };
vector<int> popV03 = { 1,2,3,4,5 };
so.IsPopOrder(pushV, popV03);
//cout<<so.IsPopOrder(pushV,popV02)<<endl;
cout << endl;
return 0;
}
注意:设置另一个栈,用来模拟压如和弹出过程
1.push为压入栈,pop为弹出栈
2.push 从前往后一个元素一个元素的压入temp栈:temp每增加一个元素,push就会减少一个元素
3.如果temp栈的栈顶元素和pop栈的栈尾元素相等,删除temp的栈顶元素和pop栈的栈尾元素;再依次比较,如果两个元素相等,重复3操作;如果不等,重复2操作;
4.循环终止条件:pop为空;或push为空且temp的栈顶元素不等于pop的栈尾元素