import java.util.Stack;
/**
* 判断出栈序列是否可能
*
* @author VIC
*
*/
public class IsPopSeq {
/**
*
* @param pPush 给定的入栈序列
* @param pPop 需要判断是否可能的出栈序列
* @return
*/
public static boolean isPopOrder(int[] pPush, int[] pPop) {
if (pPush == null || pPop == null || pPush.length == 0
|| pPop.length == 0 || pPop.length > pPush.length)
return false;
Stack<Integer> stack = new Stack<>();
int pushIndex = 0, popIndex = 0;
while (popIndex < pPop.length) {
while (stack.isEmpty() || stack.peek() != pPop[popIndex]) {
if (pushIndex == pPush.length) {
break;
}
stack.push(pPush[pushIndex++]);
}
if (stack.peek() != pPop[popIndex]) {
return false;
} else {
stack.pop();
popIndex++;
}
}
if (popIndex == pPop.length)
return true;
return false;
}
public static void main(String[] args) {
int[] pPush = { 1, 2, 3, 4, 5 };
int[] pPop = { 1, 2, 3, 4, 5, 6 };
System.out.println(isPopOrder(pPush, pPop));
}
}
栈的压入弹出序列
最新推荐文章于 2018-05-21 16:25:24 发布