栈的压入、弹出序列 java实现

来源:互联网 发布:淘宝助理6.0官方下载 编辑:程序博客网 时间:2024/06/06 07:36


输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。



public static boolean IsPopOrder(int [] pushA,int [] popA) {boolean result = false;if (pushA.length ==0 && popA.length ==0) {return true;}if (pushA.length == popA.length) { Stack<Integer>  stack  = new Stack<Integer>();    int j =0;    for (int i = 0; i < popA.length; i++) {if (pushA[i] == popA[j]) {j++;while(!stack.isEmpty()&& j < popA.length ){int p = stack.pop();if (p == popA[j]) {j++;}else{stack.push(p);break;}}}else {stack.push(pushA[i]);}}    while(j < popA.length  ){    int k = stack.pop();    if (popA[j] == k) {j++;}else {stack.push(k);break;}    }    if (stack.isEmpty()) {return true;}}    return result;}


0 0