栈的压入、弹出序列

来源:互联网 发布:苏州淘宝代运营公司 编辑:程序博客网 时间:2024/05/21 09:29
package com.google.android;import java.util.Stack;public class StackPopOrderChecker {public static void main(String[] args) {// 进栈序列int[] pPush = { 1, 2, 3, 4, 5 };// 出栈序列int[] pPop = { 4, 3, 5, 1,2 };//{6,4, 3, 5, 2, 1 };//{ 4, 3, 5, 2, 1 };boolean flag = new StackPopOrderChecker().check(pPush, pPop);System.out.println(flag);}public boolean check(int[] pPush, int[] pPop) {boolean isPossiable = false;if (pPush != null && pPop != null) {Stack<Integer> stack = new Stack<Integer>();int i = 0, j = 0;// 检查每个出栈while (j < pPop.length) {while (i < pPush.length && pPop[j] != pPush[i]) {// 如果不等,则一直进栈stack.push(pPush[i]);++i;}//相等的元素没有进栈++i;++j;int top = 0;// 出栈比较while ((!stack.empty()) && (top = stack.pop()) == pPop[j]) {++j;}if (j < pPop.length) {stack.push(top);}// 当已经找不到进栈元素时退出if (i >= pPush.length && !stack.empty()) {break;}}if (stack.empty()) {isPossiable = true;}}return isPossiable;}}

0 1
原创粉丝点击