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;
}
}
剑指offer--栈的压入、弹出序列
最新推荐文章于 2023-02-20 09:12:06 发布