【发布时间】:2014-11-15 03:24:01
【问题描述】:
我正在尝试创建一个适用于linkedList 的迭代器。我已经创建了我认为应该可以正常工作的链接列表,但现在我需要帮助来创建迭代器。我试图让它比简单地使用带有 for 循环的 getEntry() 更快,每次增加一个,因为使用该方法意味着我必须遍历每个元素的链表。我试图比这更快地解决它,但不知道从哪里开始。我知道我需要创建 next 和 hasext 方法,但不知道如何创建。还卡在构造函数和实例方法上。
这是我目前的代码:
import java.util.NoSuchElementException;
public class SListIterator<T>
{
private Node firstNode;
private int numberOfEntries;
public SListIterator()
{
firstNode = null;
numberOfEntries = 0;
}
public void addToFirst(T aData)
{
firstNode = new Node(aData, firstNode);
numberOfEntries++;
}
public T getEntry(int givenPosition)
{
T result = null;
if((givenPosition >= 1) && (givenPosition <= numberOfEntries))
{
result = (getNodeAt(givenPosition)).data;
}
return result;
}
private Node getNodeAt(int givenPosition)
{
Node currentNode = firstNode;
for(int counter = 1; counter < givenPosition; counter++)
{
currentNode = currentNode.next;
}
return currentNode;
}
public Iterator<T> getIterator()
{
// TO DO
}
private class IteratorForSList implements Iterator<T>
{
// instance variable for IteratorForSList
private IteratorForSList()
{
// constructor
}
public boolean hasNext()
{
// need help
}
public T next()
{
// need help
}
public T remove()
{
throw new UnsupportedOperationException("remove() is not supported by this iterator");
}
}
private class Node
{
private T data;
private Node next;
private Node(T aData, Node nextNode)
{
data = aData;
next = nextNode;
}
}
}
【问题讨论】: