一个序列是否可能是push序列的pop序列

           输入:两个序列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


版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/Rex7/p/4752555.html