劍指offer——(19)棧的壓入、彈出序列
阿新 • • 發佈:2019-01-05
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]; } }