题意:栈元素的压入、弹出
思路:给出了压入的顺序和弹出的次序,需要搞一个栈来存储压入的数组元素,然后进行比较。具体看代码。
package MianShiTi_22;
import java.util.Stack;
public class MianShiTi_22 {
//只有当要弹出的元素恰好是栈顶元素,那么直接弹出。
//若下一个弹出的元素不在栈栈顶,那么把压栈顺序中还没有压入的元素压入辅助栈,直到把下一个需要弹出的元素压入栈。
//如果所有元素都压入栈仍然没有找到下一个弹出的数字,那么该序列不可能是一个弹出序列。
public static boolean isPopOrder(int[] push , int[] pop) {
if(push == null || pop ==null || push.length!= pop.length){
return false;
}
int popFirst = 0;//指向pop数组的首个元素
int pushFirst = 0;//指向push数组的首个元素
int popIndex = 0;//指向pop数组要指向的元素
int pushIndex = 0;//指向push数组的要指向元素
Stack<Integer> stack = new Stack<>();
stack.push(push[pushFirst]);
while(popIndex-popFirst < pop.length){
//这个if判断就是为了防止在pop数组为{1,2,3,4,5}这种情况的时候,做出处理。
if(stack.isEmpty()){
stack.push(push[pushIndex]);
}
while((pushIndex - pushFirst < push.length) && (stack.peek() != pop[popIndex] || stack.isEmpty())) {
stack.push(push[pushIndex]);
pushIndex++;
}
if(stack.peek() == pop[popIndex]){
stack.pop();
popIndex++;
}
else{
return false;
}
}
return true;
}
public static void main(String[] args) {
int[] push = {1,2,3,4,5};
int[] pop1 = {4,5,3,2,1};
int[] pop2 = {4,5,3,1,2};
int[] pop3 = {1,2,3,4,5};
MianShiTi_22 test = new MianShiTi_22();
System.out.println(MianShiTi_22.isPopOrder(push, pop1));
System.out.println(MianShiTi_22.isPopOrder(push, pop2));
System.out.println(MianShiTi_22.isPopOrder(push, pop3));
}
}