不多说,上代码
package sword.to.offer;
import java.util.Stack;
public class IsPopOrder {
static boolean isPopOrder(final int[]pPush,final int[] pPop,int nLegnth){
boolean bImpossible=false;
if(pPush.length!=0&&pPop.length!=0){
java.util.Stack<Integer> stack=new Stack<Integer>();
int i=0;
int j=0;
while(j<nLegnth){
while(stack.isEmpty()||stack.peek()!=pPop[j])
{
if(i==nLegnth){
break;
}
stack.push(pPush[i]);
i++;
}
if(stack.peek()!=pPop[j])
break;
stack.pop();
j++;
}
if(stack.isEmpty()&&j==nLegnth)
bImpossible=true;
}
return bImpossible;
}
public static void main(String[] args) {
//若要验证b是a完整的pop弹出序列,各数组的个数必须
int[] a={1,2,3,4,5};
int[] b= {4,5,3,2,1};
int[]c={4,3,5,1,2};
System.out.println(isPopOrder(a, b,5));
System.out.println(isPopOrder(a, c,5));
}
}
运行结果: