JZ31 栈的压入、弹出序列
1.题目解析
题目是让我们判断是否可以完成这个pop。
可以返回true不可以返回false。
2.算法原理
要实现题目的要求,我们只需要模拟栈的push和pop操作即可。如果操作模拟下来栈里面为空,就可以实现,否则就不可以实现。
3.代码实现
#include<iostream>
#include<vector>
#include<algorithm>
#include<stack>
using namespace std;
class Solution {
public:
bool IsPopOrder(vector<int>& pushV, vector<int>& popV)
{
stack<int> st1;
int n=0;
for(int i=0;i<pushV.size() ;i++)
{
while (!st1.empty() && st1.top() == popV[n])
{
st1.pop();
n++;
}
st1.push(pushV[i]);
}
int ci=st1.size();
for(int j=0;j<ci;j++)
{
if(st1.top()==popV[n])
{
st1.pop();
n++;
}
}
if(st1.empty())
{
return true;
}
else
{
return false;
}
}
};