剑指Offer22题栈的压入、弹出序列 java解答(如有错误欢迎批评指正)

来源:互联网 发布:java员工管理系统 编辑:程序博客网 时间:2024/05/20 14:25

package test;import java.util.Stack;public class IsPopOrder {public boolean isPopOrder(int[] push, int[] pop){boolean possible = false;if(push.length>0 && pop.length>0){int countPush = -1;int countPop = 0;int nextPush = 0;int nextPop = pop[countPop];Stack<Integer> stack = new Stack<>();while(countPop<pop.length){while(stack.isEmpty() || stack.peek() != nextPop){++countPush;if(countPush == push.length){break;}nextPush = push[countPush];stack.add(nextPush);}if(stack.peek() != nextPop){break;}stack.pop();++countPop;if(countPop != push.length){nextPop=pop[countPop];}else{break;}}if(stack.isEmpty() && nextPop==pop[pop.length-1])possible = true;}return possible;}public static void main(String[] args) {// TODO Auto-generated method stubint[] push = {1,2,3,4,5};int[] pop = {3,2,1,5,4};System.out.println(new IsPopOrder().isPopOrder(push, pop));}}


0 0