当前位置:   article > 正文

剑指offer-例题 栈的压入、弹出序列

剑指offer-例题 栈的压入、弹出序列

题目描述

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

  1. import java.util.ArrayList;
  2. import java.util.Stack;
  3. public class Solution {
  4. public boolean IsPopOrder(int [] pushA,int [] popA) throws Exception{
  5. if(pushA==null||popA==null)
  6. return false;
  7. if(pushA.length==0||popA.length==0||pushA.length!=popA.length)
  8. return false;
  9. Stack<Integer> s=new Stack<Integer>();
  10. int index2=0;
  11. for(int index1=0;index1<pushA.length;index1++)
  12. {
  13. s.push(pushA[index1]);
  14. while(!s.empty()&&s.peek()==popA[index2]&&index2<popA.length)//这里有个坑 多个条件注意顺序
  15. //!s.empty()必须放在s.peek()的前面,否则当栈为空时会发生EmptyStackException
  16. //Stack类中的pop()、peek()方法都要先判断栈是否为空
  17. {
  18. s.pop();
  19. index2++;
  20. }
  21. }
  22. return s.empty();
  23. }
  24. }

要想出栈得先入栈

如果不符合出栈规则,则永远不会出栈,栈也不会为空

一个一个的入栈

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/201995
推荐阅读