题目:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。
例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
思路:两个数组,一个是push序列,一个是pop序列,需要两个指针,一个是pushIndex, 另一个是popIndex, 还需要一个辅助栈。当pushIndex < len(数组的长度)且 (stack为空或stack的栈顶不等于pop序列时),将push序列中的元素压入到stack中。
public class StackPushAndPop { public static void main(String[] args){ /*Scanner s = new Scanner(System.in); while(s.hasNext()){ int len = s.nextInt(); int[] push = new int[len]; for(int i =0 ; i < len;i++){ push[i] = s.nextInt(); } int[] pop = new int[len]; for(int i = 0; i < len;i++){ pop[i] = s.nextInt(); } boolean result = IsPopOrder(push,pop); System.out.println(result); }*/ int push[] = new int[]{1,2,3,4,5}; int pop[] = new int[]{5,3,4,2,1}; boolean result = IsPopOrder(push,pop); System.out.println(result); } public static boolean IsPopOrder(int[] pushA, int[] popA) { Stack<Integer> stack = new Stack<Integer>(); if(pushA == null || popA == null || popA.length == 0 || pushA.length == 0 || pushA.length != popA.length){ return false; } int pushIndex = 0; int popIndex = 0; while(popIndex < popA.length){ while( (pushIndex < pushA.length) && (stack.isEmpty() || popA[popIndex] != stack.peek())) { stack.push(pushA[pushIndex]); pushIndex++; } if(stack.peek() == popA[popIndex]){ stack.pop(); popIndex++; }else{ return false; } } return true; } }