剑指offer——(19)栈的压入、弹出序列

版权声明:本文自由转载,转载请注明出处。 https://blog.csdn.net/qq_38071429/article/details/84556358

public class Solution {
        int top;
        int[] A; // 数组栈
   public boolean IsPopOrder(int[] pushA, int[] popA) {
		if(pushA.length==1&&popA[0]==pushA[0]) return true;
		top = -1;
		A = new int[pushA.length];
		int in = 1, out = 0;
		while (in <= pushA.length + 1 && out < pushA.length) {
            // 依次拿栈顶元素与弹出序列的元素比较是否相等
			if (Peek() == popA[out]) {
				Pop(); // 相等就弹出数组栈的栈顶元素
				out++;
			} else {
                // 否则存入数组栈
				if (in <= pushA.length) {
					if(in==pushA.length) Push(pushA[in-1]);
					else Push(pushA[in]);
					//++top;
				}
					
				in++;
			}
			  for(int i=0;i<A.length;i++){
				  System.out.print(A[i]+" ");
		        }
			  System.out.println(out);
		}
		
		if (out == popA.length-1 && pushA.length != 1)
			return true;
		else
			return false;
	}

	public void Push(int str) {
		A[++top] = str; // 按顺序存进"栈"(数组形式)
	}

	public int Pop() {
		if (top < 0) return -1;
		top--;
		return A[top + 1];
	}

	public int Peek() {
		//if (top < 0) return -1;
		return top < 0?-1:A[top];
	}

}

猜你喜欢

转载自blog.csdn.net/qq_38071429/article/details/84556358
今日推荐