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 withi=0
andi=1
. You can fix this by changingi<=k
toi<k
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) {
}
You're off by one. You want
If there's more problems, you need to provide more code and questions.
while
loop until the stack is exhausted, which is probably not what you want. If you want to check whether there are elements in the stack, use anif
statement.this.pop()
four times.while
with anif
, you only check that there is one element is on the stack, but you may callpop()
multiple times. You should do the check inside the loop or move the check insidepop()
.There are a few issues with this:
for (... ; i<=k && stack.canPop(); ...
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.