在双向链表中实现previous()和hasPrevious()方法

时间:2015-09-23 19:30:42

标签: java iterator doubly-linked-list

我正在用迭代器编写doubly linked list。我设法实现了next()hasNext()方法。它工作正常,我在前进遍历后得到了预期的结果。但我陷入了如何实施previous()hasPrevious()的困境。我在这里做了什么:

private class ListIterator<E> implements java.util.ListIterator<E> { 
        private Node<E> current = (Node<E>) head;
        private Node<E> last = (Node<E>) tail;

        public ListIterator() {

        }

        public ListIterator(int index) {
            if (index < 0 || index > size)
                  throw new IndexOutOfBoundsException();
                for (int i = 0; i < index; i++)
                  current = current.next;
        }

        @Override
        public boolean hasNext() {
            return (current != null);
        }

        @Override
        public boolean hasPrevious() {
            return  last != null;
        }

        @Override
        public E next() {  
            E e = current.element;
            current = current.next;
            return e;
        }

        @Override
        public E previous() {
            E e = (E) last.element;
            last = last.previous;
            return e;
        }

当我想要向后遍历时,我正在获取List中的最后一个元素:

[11, 10, 9, 8, 7, 6, 5] //list
 11 10 9 8 7 6 5 //Forward traversing 
 5   //Backwards traversing

我做错了什么?为什么我无法遍历整个List

1 个答案:

答案 0 :(得分:0)

我没有理由跟踪最后一个元素。只是当前的一个。您可以使用current.previous

实现previous()