Java Stack method (multipop) Beginner java
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开发者_JS百科 help out there?
public void multipop(int k) {
while (top != null) {
for (int i = 0; i <= k; i++) {
this.pop();
}
}
}
- You execute the
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. - In the loop, you iterate from 0 to k, inclusive. This means that if k = 3, you go through 0, 1, 2 and 3 and thus call
this.pop()
four times. - Even if you replace the
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()
. - The indentation is horrible :)
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();
}
}
精彩评论