package test;
import java.util.Stack;
public class IsPopOrder {
public boolean isPopOrder(int[] push, int[] pop){
boolean possible = false;
if(push.length>0 && pop.length>0){
int countPush = -1;
int countPop = 0;
int nextPush = 0;
int nextPop = pop[countPop];
Stack<Integer> stack = new Stack<>();
while(countPop<pop.length){
while(stack.isEmpty() || stack.peek() != nextPop){
++countPush;
if(countPush == push.length){
break;
}
nextPush = push[countPush];
stack.add(nextPush);
}
if(stack.peek() != nextPop){
break;
}
stack.pop();
++countPop;
if(countPop != push.length){
nextPop=pop[countPop];
}else{
break;
}
}
if(stack.isEmpty() && nextPop==pop[pop.length-1])
possible = true;
}
return possible;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] push = {1,2,3,4,5};
int[] pop = {3,2,1,5,4};
System.out.println(new IsPopOrder().isPopOrder(push, pop));
}
}