剑指offer--算法题--23--栈的压入弹出序列

规律:如果下一个弹出的数字刚好是栈顶的数字,那么直接弹出。如果下一个弹出的数字不在栈顶,我们把压栈序列中还没有入栈的数字压入辅助栈,直到把下一个需要弹出的数字压入栈顶为止。如果所有的数字都压入栈了,仍没有找到下一个弹出的数字,那么该序列不可能是一个弹出序列

步骤

操作

弹出数字

1

压入1

1

2

压入2

1,2

3

压入3

1,2,3

4

压入4

1,2,3,4

5

弹出

1,2,3

4

6

压入5

1,2,3,5

7

弹出

1,2,3

5

8

弹出

1,2

3

9

弹出

1

2

10

弹出

1

package jzoffer;

import java.util.Stack;

public class E22StackPushPopOrder {
	public boolean check(int[] pPush,int[]pPop){
		boolean isPossible = 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()){
				isPossible = true;
			}
		}
		return isPossible;
		
	}
	public static void main(String[] args) {
		//进栈序列
		int[] pPush = {1,2,3,4,5};
		System.out.println("1,2,3,4,5");
		//出栈序列
		int[] pPop  = {4,3,5,2,1};
		System.out.println("4,3,5,2,1");
		boolean flag = new E22StackPushPopOrder().check(pPush, pPop);
		System.out.println(flag);
	}

}

结果图:


猜你喜欢

转载自blog.csdn.net/lsm18829224913/article/details/80528127