用java判断数据结构进出栈的顺序是否正确

//通过flag判断出栈顺序是否正确
import java.util.*;
public class E1 {


    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
//      
       int a[]={1,2,3,4,5}; //进栈顺序
       int b[]={4,5,3,1,2}; //出栈顺序
       solution i=new solution();
       i.isPopOrder( a, b);
    }
}
class solution {
    public void isPopOrder (int [] pushA,int [] popA){
        Stack<Integer> stack=new Stack<>();
        if(pushA.length==0||popA.length==0){
            System.out.println(false);
        }
        int flag=0;
        for (int i=0;i<popA.length;i++){
            stack.push(pushA[i]);
            while(!stack.empty()&&stack.peek()==popA[flag]){
                stack.pop();
                flag++;
            }
        }
        System.out.println(flag);
    }


}
posted @ 2022-11-02 16:07  Dog17  阅读(165)  评论(0)    收藏  举报