栈的压入、弹出序列
给一个入栈序列和一个出栈序列,判断出栈序列是否合法
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};
System.out.println(isPopOrder(a, b));
System.out.println(isPopOrder(a, c));
}
public static boolean isPopOrder(int[] pushOrder, int[] popOrder) {
Stack<Integer> stack = new Stack<>();
int flag = 0;
for (int i = 0; i < pushOrder.length; i++) {
stack.push(pushOrder[i]);
while (!stack.isEmpty() && popOrder[flag] == stack.peek()) {
stack.pop();
flag++;
}
}
return stack.isEmpty();
}

浙公网安备 33010602011771号