它工作正常,直到它进入最后一个对象添加到nonEmptyList
在sample()
方法给我正确的输出。我已经设法找出它在哪里循环,这在add(item)
方法的while循环中。我不能改变方法或返回,所以如果任何人可以提出一种方法,我可以防止这种无限循环,这将不胜感激。我为什么要进入循环?
public class SampleableListImpl implements SampleableList {
public int size;
public Object firstLink = null; //Made a link class to manage each object, this class is the linkedlist (manager) of the object private
public ReturnObjectImpl ro;
int count;
SampleableListImpl emptyList;
SampleableListImpl nonEmptyList;
public ReturnObject add(Object item) {
if (firstLink == null){
firstLink = item;
size++;
firstLink.setIndex(0);
System.out.println("Added linkedlink at 0");
} else if (firstLink != null){
Object current = firstLink;
while (current.getNextNode() != null){ //LOOPS HERE AFTER sample() sends the last object to be added to nonEmptyList
current = current.getNextNode();
}
current.setNextNode(item);
size++;
current.getNextNode().setIndex(size - 1);
System.out.println("Added a new link to the existing linkedlist at " + current.getNextNode().getIndex());
}
return null;
}
public SampleableList sample() {
if (firstLink == null){
System.out.println("List is empty, so returning an empty sampableList");
return emptyList = new SampleableListImpl();
}
Object current = firstLink;
if (firstLink.getNextNode().getNextNode() != null){
nonEmptyList = new SampleableListImpl();
System.out.println("Adding to firstNode in nonEmptyList");
nonEmptyList.add(firstLink);
while (current.getNextNode().getNextNode() != null){
current = current.getNextNode().getNextNode();
System.out.println("Adding " + current.getIndex() + " to nonEmptyList");
nonEmptyList.add(current);
}
} else {
nonEmptyList.firstLink = current;
System.out.println("There is only a head - no other objects to sample");
}
System.out.println("returning nonEmptyList");
return nonEmptyList;
}
}
而且我正在这个
SampleableListImpl sampList = new SampleableListImpl();
Object ob = new Object();
Object ob1 = new Object();
Object ob2 = new Object();
Object ob3 = new Object();
Object ob4 = new Object();
sampList.add(ob);
sampList.add(ob1);
sampList.add(ob2);
sampList.add(ob3);
sampList.add(ob4);
sampList.sample();
不知道,但双看aheads'link.getNextNode()。getNextNode()'是臭。 – weston
我应该解释一下,示例返回列表中的第一个,第三个,第五个...对象。 – BitLord
你必须把它绑在一个圆圈里,这是循环要做的唯一方法。那么你是什么意思,你不能改变方法或回报?唯一剩下的就是用法。因此请显示使用情况。 – weston