public class 面试题22_栈的压入和弹出 {
/*
题目描述
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为
该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈
的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就
不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
笔
*/
public static void main(String[] args) {
int[] a={1,2,3,4,5};
int[] b={4,5,3,2,1};
int[] c={4,3,5,1,2};
int[] d={1,3,2,4,5};
int[] e={2,3,5,4,1};
int[] f={5,4,3,2,1};
int[] g={1,2};
System.out.println(isPopOrder(a, g));
}
public static boolean isPopOrder(int[] a,int[] b){
if(a==null||b==null||a.length!=b.length){
return false;
}
int index1=0;
int index2=0;
Stack<Integer> st=new Stack<Integer>();
while(index1<a.length&&index2<b.length){
if(!st.isEmpty()){
if(st.peek()==b[index2]){
st.pop();
index2++;
}else{
st.push(a[index1++]);
}
}else{
st.push(a[index1++]);
}
}
while(!st.isEmpty()&&st.peek()==b[index2]){
st.pop();
index2++;
}
if(st.isEmpty()&&index2>=b.length-1){
return true;
}
return false;
}
}