剑指offer--栈的压入、弹出序列

来源:互联网 发布:es大数据实时分析 编辑:程序博客网 时间:2024/06/18 06:12
import java.util.Stack;/** * 栈的压入,弹出序列 题目:输入两个整数序列,第一个序列表示栈的压入顺序 * ,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不等。例如,序列{1,2,3,4,5}是某栈的压栈顺序,序列{4,5,3,2,1}是该栈 * 序列对应的一个弹出序列,但{4,3,5,1,2}就不可能是该压栈序列的弹出序列 * */public class 面试题31 {    public static void main(String[] args) {        int[] push1 = { 1, 2, 3, 4, 5 };        int[] pop1 = { 4, 5, 3, 2, 1 };        System.out.println(isPopOrder(push1, pop1));        int[] push2 = { 1, 2, 3, 4, 5 };        int[] pop2 = { 4, 3, 5, 1, 2 };        System.out.println(isPopOrder(push2, pop2));        int[] push3 = { 1 };        int[] pop3 = { 1 };        System.out.println(isPopOrder(push3, pop3));    }    public static boolean isPopOrder(int push[], int[] pop) {        if (pop == null || push == null || pop.length != push.length)//异常输入判断            return false;        Stack<Integer> stack = new Stack<Integer>();        int pop_index = 0, push_index = 0;        while (pop_index < pop.length) {            int head = pop[pop_index];            if (stack.size() == 0 || stack.peek() != head) {    //如果此时栈为空或者栈顶不是出栈序列的头节点                while (push[push_index] != head) {  //在入栈序列中搜索头节点                    stack.push(push[push_index]);   //入栈序列中的元素入栈                    push_index++;                    if (push_index >= push.length)                        return false;                }                if (push_index < push.length - 1)                      push_index++; //找到出栈的头结点,此时的入栈节点位置++            } else if (stack.peek() == head) {  //如果此时的栈顶等于头结点                stack.pop();    //栈顶出栈            }            System.out.println(head);            pop_index++;//找下一个出栈节点        }        return true;    }}