赞
踩
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
- import java.util.ArrayList;
- import java.util.Stack;
- public class Solution {
- public boolean IsPopOrder(int [] pushA,int [] popA) throws Exception{
- if(pushA==null||popA==null)
- return false;
- if(pushA.length==0||popA.length==0||pushA.length!=popA.length)
- return false;
- Stack<Integer> s=new Stack<Integer>();
- int index2=0;
- for(int index1=0;index1<pushA.length;index1++)
- {
- s.push(pushA[index1]);
- while(!s.empty()&&s.peek()==popA[index2]&&index2<popA.length)//这里有个坑 多个条件注意顺序
- //!s.empty()必须放在s.peek()的前面,否则当栈为空时会发生EmptyStackException
- //Stack类中的pop()、peek()方法都要先判断栈是否为空
- {
- s.pop();
- index2++;
- }
- }
- return s.empty();
- }
- }

要想出栈得先入栈
如果不符合出栈规则,则永远不会出栈,栈也不会为空
一个一个的入栈
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。