简体   繁体   English

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

[英]Implementation of previous() and hasPrevious() method in a doubly linked lists

I am writing a doubly linked list with an iterator. 我正在用迭代器编写一个doubly linked list I managed to implement the next() and the hasNext() methods. 我设法实现了next()hasNext()方法。 It works fine, and I am getting the expected result after a forward traversing. 它工作正常,向前遍历后,我得到了预期的结果。 But I am stuck in how to implement previous() and hasPrevious() . 但是我被困在如何实现previous()hasPrevious() Here what I did: 这是我做的:

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;
        }

I am getting just the last element in my List when I want a backwards traversing: 当我想向后遍历时,我得到的只是List的最后一个元素:

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

What I am doing wrong? 我做错了什么? Why can't I traverse backwards through the whole List ? 为什么我不能遍历整个List

I don't see a reason to track the last element. 我没有找到追踪最后一个元素的理由。 Just current one. 只是当前的。 You could implement previous() using current.previous 您可以使用current.previous实现previous()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM