栈的压入、弹出序列

给一个入栈序列和一个出栈序列,判断出栈序列是否合法

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

posted @ 2017-09-05 15:44  被罚站的树  阅读(88)  评论(0)    收藏  举报