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

来源:互联网 发布:js 原型 编辑:程序博客网 时间:2024/05/01 22:16

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


0 0
原创粉丝点击