校验出栈顺序

2017-05-16  本文已影响91人  senninha

给定入栈顺序,给出一组出栈顺序,判断是否满足条件

public static boolean isOutStack(int[] inBound,int[] outBound){
        Stack<Integer> stack = new Stack<Integer>();
        //进栈的下标
        int in = 0;
        //出栈的下标
        int out = 0;
        
        //当出栈的下标到5时,循环停止
        while(out != outBound.length){
            //当进栈为完时
            if(in < inBound.length){
                //如果进的那个等于出的那个,直接下标各自+1
                if(inBound[in] == outBound[out]){
                    out++;
                    in++;
                //如果不相等,这时候如果栈不为空,要考虑当前出栈的元素与栈顶的元素是否相同
                }else if(stack.size() > 0){
                    int tem = stack.pop();
                    //若相同,则把它出栈,出栈下标+1
                    if(tem == outBound[out]){
                        out++;
                    //否则,入栈当前元素,入栈+1
                    }else{
                        stack.push(tem);
                        stack.push(inBound[in]);
                        in++;
                    }
                //栈为空,将元素入栈
                }else{
                    stack.push(inBound[in]);
                    in++;
                }
                //无入栈元素时,直接出栈栈顶元素,与出栈序列比较,若不同,false,否则继续
            }else{
                int tem = stack.pop();
                if(tem == outBound[out]){
                    out++;
                }else{
                    return false;
                }
            }
        }
        return true;
    }
上一篇下一篇

猜你喜欢

热点阅读