为LinkedList编写自己的迭代器

时间:2016-02-08 05:56:10

标签: java linked-list singly-linked-list

我已经为ArrayList编写了这个Iterator,但现在我需要为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;
}

}

我真的迷失在哪里,所以我非常感谢一些帮助

1 个答案:

答案 0 :(得分:0)

在查看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方法,以供参考。 希望它可能会有所帮助。