import java. util. Stack;
public class E31PushPopSequence {
public static boolean isPopOrder ( int [ ] push, int [ ] pop, int length) {
if ( push == null || pop == null || length <= 0 )
return false ;
Stack< Integer> stack = new Stack < > ( ) ;
int pushIndex = 0 ;
int popIndex = 0 ;
while ( popIndex < length) {
while ( stack. empty ( ) ||
( pushIndex < length && stack. peek ( ) != pop[ popIndex] ) ) {
stack. push ( push[ pushIndex] ) ;
pushIndex++ ;
}
if ( stack. peek ( ) != pop[ popIndex] )
break ;
stack. pop ( ) ;
popIndex++ ;
}
return stack. empty ( ) && popIndex == length;
}
public static void main ( String[ ] args) {
int [ ] push = { 1 , 2 , 3 , 4 , 5 } ;
int [ ] pop1 = { 5 , 4 , 3 , 2 , 1 } ;
int [ ] pop2 = { 4 , 5 , 3 , 2 , 1 } ;
int [ ] pop3 = { 4 , 3 , 5 , 1 , 2 } ;
System. out. println ( E31PushPopSequence. isPopOrder ( push, pop1, 5 ) ) ;
System. out. println ( E31PushPopSequence. isPopOrder ( push, pop2, 5 ) ) ;
System. out. println ( E31PushPopSequence. isPopOrder ( push, pop3, 5 ) ) ;
}
}