I'm trying to write a Java method to preform a "multi-pop" off a stack.
It should perform a "pop" operation on a stack
object k
number of times. This is what I'm thinking, but it's not quite right. Any help out there?
public void multipop(int k) {
while (top != null) {
for (int i = 0; i <= k; i++) {
this.pop();
}
}
}
Looks like an off-by-one error.
If k=1
, you will go through the loop with i=0
and i=1
. You can fix this by changing i<=k
to i<k
There are a few issues with this:
- The brackets should be better formatted [the first look lead me to believe a mismatch]
- Your check for the null case should be in the middle of the for loop:
for (... ; i<=k && stack.canPop(); ...
- You need a method to check to make sure that there is an item that you can pop.
- As the other answer states, there is an off by one error, if you wish to pop up to K items, then the condiction should be i < k.
This should run into an exception or an infinite loop because the first loop makes sure that there is still a "top" variable that isn't null, and then it directs it to the second loop that goes from 0:k.
You're off by one. You want
for(int i =0; i < k; i++)
If there's more problems, you need to provide more code and questions.
1st, it loops (k+1) times, from 0 to k.
2nd, after several pops, it is possible that top is null. So it needs check top all the time.
It could be modified as below:
public void multipop(int k) {
for (int i = 0; top != null && i < k; i++) {
this.pop();
}
}