0

这是我的 Swing 类中的一个辅助方法。我正在编写一个程序,根据树木的数量和高度,计算猴子可以在它们之间摆动的可能的树对。

public class Swing {

 private long processSwing(int N, Scanner sc){
  int i=0;
  long count=0;
  Stack<Integer> s1 = new Stack<>();
  while(i<N){//scanning loop
   int currTree=sc.nextInt();
   if(s1.isEmpty()){//if s1 is empty(only will happen at the first tree, because consequently s1 will always be filled)
    s1.push(currTree);//push in first tree
   }
   else{
    while(currTree>s1.peek()){//this loop removes all the previous trees which are smaller height, and adds them into pair counts
     s1.pop();
     count++;
    }
    if(!s1.isEmpty()){//if the stack isnt empty after that, that means there is one tree at the start which is same height or bigger. add one pair.
     count++;
    }
    if(currTree==s1.peek()){
     s1.pop();
    }
    s1.push(currTree);// all trees will always be pushed once. This is to ensure that the stack will never be empty.
   }//and the tree at the lowest stack at the end of every iteration will be the tallest one
   i++;
  }
  return count;
 }
}

这部分确保如果堆栈 s1 为空,它将把我扫描到的第一个整数压入堆栈。

if(s1.isEmpty()){
     s1.push(currTree);//push in first tree
}

随后, else 条件运行:

 else{
    while(currTree>s1.peek()){
     s1.pop();
     count++;
    }
    if(!s1.isEmpty()){
     count++;
    }
    if(currTree==s1.peek()){
     s1.pop();
    }
    s1.push(currTree);
    }

代码成功压入第一个整​​数后,将抛出 EmptyStackException,for s1.peek() 方法在该行

 while(currTree>s1.peek())

为什么会这样?我的意思是我已经检查过,当第二次迭代运行时 s1 不是空的。

4

2 回答 2

0

您的循环可能会删除 的所有元素,Stack此时Stack将变为空并s1.peek()引发异常。

为了防止这种情况发生,请在循环中添加一个条件:

while(!s1.isEmpty() && currTree>s1.peek()) {
  s1.pop();
  count++;
}
于 2016-03-21T08:02:00.863 回答
0

您删除了 中的对象s1.pop();,因此在最后一次迭代s1中为空。您需要s1peek(). 改成

while(!s1.isEmpty() && currTree > s1.peek()) {
    s1.pop();
    count++;
}
于 2016-03-21T08:02:14.070 回答