import java.util.Stack;
public class E31PushPopSequence {
//根据入栈序列判断出栈序列是否正确
public static boolean isPopOrder(int[] push, int[] pop, int length){
if (push == null || pop == null || length <= 0)
return false;
Stack<Integer> stack = new Stack<>();
int pushIndex = 0; //下一个要入栈的元素索引
int popIndex = 0; //下一个要出栈的元素索引
while(popIndex < length) {
//一直入栈直到找到当前需要出栈元素
while (stack.empty() ||
(pushIndex < length && stack.peek() != pop[popIndex])) {
stack.push(push[pushIndex]);
pushIndex++;
}
//剩余入栈序列中没有找到则跳出循环
if (stack.peek() != pop[popIndex])
break;
//将找到的元素出栈
stack.pop();
popIndex++;
}
//栈为空,且出入栈序列都遍历完成时返回true(入栈序列一定会完成遍历)
return stack.empty() && popIndex == length;
}
//测试用例
public static void main(String[] args){
int[] push = {1, 2, 3, 4, 5};
int[] pop1 = {5, 4, 3, 2, 1};
int[] pop2 = {4, 5, 3, 2, 1};
int[] pop3 = {4, 3, 5, 1, 2};
System.out.println(E31PushPopSequence.isPopOrder(push, pop1, 5));
System.out.println(E31PushPopSequence.isPopOrder(push, pop2, 5));
System.out.println(E31PushPopSequence.isPopOrder(push, pop3, 5));
}
}
栈的压入、弹出序列(Java实现)
最新推荐文章于 2021-05-31 16:35:03 发布