为 LinkedList 编写自己的迭代器



我已经为ArrayList编写了这个迭代器,但现在我需要为LinkedList编写一个迭代器。关于如何使此代码更有效率的任何建议?

public class MyLinkedListIterator<T> implements Iterator<T> 
{
    //The list over which we are iterating
    private MyLinkedList<T> list;
    private int curPos;
public MyLinkedListIterator(MyLinkedList<T> list)
{
    this.list = list;
    curPos = 0;
}
@Override
public boolean hasNext() {
    return curPos < list.size();
}
@Override
public T next() 
{
    T element = list.get(curPos);
    curPos++;
    return element;
}
}

如果它有帮助,这是我的ListNode类,它跟踪LinkedList上的指针

public class ListNode<T> 
{
private T value;
private ListNode<T> next;

public ListNode(T value, ListNode<T> next)
{
    this.value = value;
    this.next = null;
}
public ListNode(T value)
{
    this(value, null);
}
public T getValue() {
    return value;
}
public ListNode<T> getNext() {
    return next;
}
public void setNext(ListNode<T> next) {
    this.next = next;
}
}

我真的不知道该去哪里,所以我非常感谢一些帮助

在查看您的 MyLinkedListIterator 后,我刚刚用这个更改了您的 hasNext 方法

public boolean hasNext() {
        return list.getNext()==null ? false:true;
    }

并添加了一个 getCurrent 方法以从列表中获取当前元素

public T getCurrent(){
        return (T)list;
    }

最终代码如下所示

public class MyLinkedListIterator<T> implements Iterator<T> 
{
    //The list over which we are iterating
    private MyLinkedList<T> list;
    public MyLinkedListIterator(MyLinkedList<T> list)
    {
        this.list = list;
    }
    @Override
    public boolean hasNext() {
        return list.getNext()==null ? false:true;
    }
    @Override
    public T next() 
    {
        T element = (T)list.getNext();
        list = (MyLinkedList)element;
        return element;
    }
    public T getCurrent()
    {
        return (T)list;
    }
    public static void main(String[] args) {
        MyLinkedList<Integer> m =new MyLinkedList(new Integer(10));
        MyLinkedList<Integer> m1 =new MyLinkedList(new Integer(11));
        MyLinkedList<Integer> m2 =new MyLinkedList(new Integer(12));
        MyLinkedList<Integer> m3 =new MyLinkedList(new Integer(13));
        m.setNext(m1 );
        m1.setNext(m2 );
        m2.setNext(m3 );
        MyLinkedListIterator<MyLinkedList<Integer>> it =new MyLinkedListIterator(m);
        System.out.println(((MyLinkedList)it.getCurrent()).getValue());
        while(it.hasNext()){
            System.out.println(((MyLinkedList)it.next()).getValue());
        }
    }
}

还附加了一个成功运行的 main 方法以供参考。希望它可能会有所帮助。

相关内容

  • 没有找到相关文章

最新更新