如何使用Iterator next()方法生成LinkedSet的幂集



对于我的类,我必须创建一个迭代器,它将生成LinkedSet的幂集。根据我的教授的说法,我必须遍历int current的bitString。其中current是我们要向其添加主集合元素的子集。我一直有一个NullPointerException。我认为我正确地循环了bitString,但当我想移动到集合中的下一个节点时,它会说它为null。我已经看了12个小时了,不知道该怎么办。我的教授提供了一个框架,所以我会解释什么是我的,什么是他的。

这就是框架:

private class LinkedSetPowerSetIterator implements Iterator<Set<T>> {
// cardinality of this set
int N;
// cardinality of the power set (2^N)
int M;
// the integer identifier of the current subset, i.e. the current element
// of the power set. Legal values range from 0..M-1 inclusive.
int current;
public LinkedSetPowerSetIteratorInt32BitString() {
// initialize N, M, and current here
}
public boolean hasNext() {
return current < M;
}
public Set<T> next() {
LinkedSet<T> s = new LinkedSet<T>();
char[] bitstring = Integer.toBinaryString(current).toCharArray();
// iterate from right to left over bitstring and the internal
// linked list to ensure that the call to add will insert a new
// first node (constant time)

current = current + 1;
return s;
}
public void remove() {
}
}

到目前为止我所拥有的:

private class myPowerIterator implements Iterator<Set<T>> {
// cardinality of set
int N;
// cardinality of power set (2^N)
int M;
//current subset in power set
int current;
// starting node, rear node
Node set = rear;


public myPowerIterator() {
N = size;
M = (int)Math.pow(2, N);
current = 0;

}

public boolean hasNext() {

return (current < M);
}

public Set<T> next() {

if (!hasNext()) {
throw new NoSuchElementException();
}  

LinkedSet<T> result = new LinkedSet<T>();


char[] bitString = Integer.toBinaryString(current).toCharArray();

for (int i = bitString.length - 1; i >= 0; i--) {
if (bitString[i] == 1) {
result.add(set.element); // How do I make sure it is adding elements
set = set.prev;          // from starting set? Keep getting Error:                          
}                           // NullPointerException: Cannot read field
else {                      // "prev" because this.set is null.
set = set.prev;
}
}  


current = current + 1;           
return result;

}

public void remove() {
throw new UnsupportedOperationException();
}
}

您需要在LinkedSet<T>中实现Iterable<T>接口。如果你不这样做,那么你的next((方法将不会"重置";它的位置,从而为您提供NullPointer。

相关内容

最新更新