输入:两个序列A、B,A作栈的push序列,判断B是否可能是A的pop序列。
~~~
#include<iostream>
#include<stack>
using namespace std;
bool solution(const int* apush, const int* apop, int len){
if(len < 1) return false;
int i = 0, j = 0;
stack<int> stack;
while(j < len || !stack.empty()){
if(i < len){
if(apush[i] != apop[j])
stack.push(apush[i++]);
else i++, j++;
}
while(!stack.empty() && stack.top() == apop[j])
stack.pop(), j++;
if(i == len && !stack.empty()) break;
}
return stack.empty() && j == len;
}
int main(){
int aPush[5] = {1, 2, 3, 4, 5};
int aPop[5] = {4, 3, 5, 2, 1};
cout<<solution(aPush, aPop, 5);
return 0;
}
//output: 1
~~~