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;
}
}