栈的压入和弹出序列

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)

对于这个题目,声明一个栈,对于一个栈而言每次都会有两种方式,要么pop要不就push,判断好对于栈目前而言时pop还是push就好

 1 import java.util.ArrayList;
 2 import java.util.Stack;
 3 public class Solution {
 4     public boolean IsPopOrder(int [] pushA,int [] popA) {
 5       Stack<Integer> stack=new Stack<Integer>();
 6         if(pushA.length<=0)
 7             return false;
 8         int n=pushA.length;
 9         int index1=0;
10         int index2=0;
11         while(index2<n)
12         {
13             if(stack.isEmpty())
14             {
15                 stack.push(pushA[index1++]);
16             }
17             else
18             {
19                   if(stack.peek()!=popA[index2])
20                  {
21                       if(index1<n)
22                         stack.push(pushA[index1++]);
23                       else
24                           return false;
25                  }
26                 else
27                 {
28                     index2++;
29                     stack.pop();
30                 }
31             }
32         }
33         return true;
34         
35     }
36 }

 

posted @ 2019-09-18 11:24  小路不会迷路  阅读(376)  评论(0)    收藏  举报