这是我的 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 不是空的。