给定一个IntegerIterator(实现hasNext,next,remove), 实现具有hasNext,next,remove
的PositiveIterator
有人能为这个问题提出一些想法吗?这不是家庭作业!
例如:
int[] a = new int[]{1,-2,-3,4,5,-6,7,-8,9};
IntegerIterator it = new IntegerIterator(a);
PositiveIterator iter = new PositiveIterator(it);
Console.WriteLine(iter.HasNext()); //true
Console.WriteLine(iter.HasNext()); //true
Console.WriteLine(iter.HasNext()); //true
Console.WriteLine(iter.Next()); //1
Console.WriteLine(iter.Next()); //4
Console.WriteLine(iter.Next()); //5
答案 0 :(得分:1)
PositiveIterator.Next
不应该成为问题。只需致电Iterator.Next
,直到价值为正。 PositiveIterator.Remove
只需要拨打Iterator.Remove
。 PositiveIterator.HasNext
是代码有点难看的原因,因为给定的方法只允许单向迭代。
class PositiveIterator:
int next = -1 //holds the next value to return
IntegerIterator iter //the integeriterator wrapped by this object
PositiveIterator(IntegerIterator it)
iter = it
//search for the first positive value for next
while iter.HasNext() AND ((next = iter.Next()) < 1)
NOOP
HasNext()
return next != -1
Next()
//the current value to return
int tmp = next
//search for the next positive value
while iter.HasNext() AND ((next = iter.Next()) < 1)
NOOP
if NOT iter.HasNext()
next = -1 //no next positive value available
return tmp
Remove()
if next == -1
return
iter.Remove()
//update the next value
next = Next()
基本上PositiveInteger
需要预测接下来要返回的值的值。
答案 1 :(得分:0)
这非常简单 - 覆盖构造函数,HashNext()
和Next()
方法,这样你就可以随时使用&#34;&#34;下一个正值,同时跳过所有负值。
伪代码:
class PositiveIterator:
private int next = -1;
private final Integer i;
PositiveIterator(Itertor i):
while (i.HashNext() && (next = i.Next()) <= 0) ;
//at this point next holds the next positive element, if such exists
this.i = i;
boolean HasNext():
return (next > 0)
int Next():
int tempVal = -1;
while (i.HashNext() && (tempVal = i.Next()) <= 0) ;
int res = next;
next = tempVal;
return next;
请注意,在任何方法中,任何方法 - next > 0
当且仅当数组中还有一些正元素,并且它将保存您需要生成的下一个元素。