剑指offer_22

题意:栈元素的压入、弹出
思路:给出了压入的顺序和弹出的次序,需要搞一个栈来存储压入的数组元素,然后进行比较。具体看代码。

package MianShiTi_22;

import java.util.Stack;

public class MianShiTi_22 {

    //只有当要弹出的元素恰好是栈顶元素,那么直接弹出。
    //若下一个弹出的元素不在栈栈顶,那么把压栈顺序中还没有压入的元素压入辅助栈,直到把下一个需要弹出的元素压入栈。
    //如果所有元素都压入栈仍然没有找到下一个弹出的数字,那么该序列不可能是一个弹出序列。
    public static boolean isPopOrder(int[] push , int[] pop) {
        if(push == null || pop ==null || push.length!= pop.length){
            return false;
        }
        int popFirst = 0;//指向pop数组的首个元素
        int pushFirst = 0;//指向push数组的首个元素
        int popIndex = 0;//指向pop数组要指向的元素
        int pushIndex = 0;//指向push数组的要指向元素      
        Stack<Integer> stack = new Stack<>();
        stack.push(push[pushFirst]);
        while(popIndex-popFirst < pop.length){
            //这个if判断就是为了防止在pop数组为{1,2,3,4,5}这种情况的时候,做出处理。
            if(stack.isEmpty()){
                stack.push(push[pushIndex]);
            }
                while((pushIndex - pushFirst < push.length) && (stack.peek() != pop[popIndex] || stack.isEmpty())) {
                stack.push(push[pushIndex]);
                pushIndex++;
                }
                if(stack.peek() == pop[popIndex]){
                stack.pop();
                popIndex++;
                }
            else{
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        int[] push = {1,2,3,4,5};
        int[] pop1 = {4,5,3,2,1};
        int[] pop2 = {4,5,3,1,2};
        int[] pop3 = {1,2,3,4,5};
        MianShiTi_22 test = new MianShiTi_22();
        System.out.println(MianShiTi_22.isPopOrder(push, pop1));
        System.out.println(MianShiTi_22.isPopOrder(push, pop2));
        System.out.println(MianShiTi_22.isPopOrder(push, pop3));
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值