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

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值