java - ListIterator 类的 Previous() 方法

标签 java doubly-linked-list

我的输出在不应该打印元素的同时打印 null 。例如,

        MyList<String> l = new MyList<String>();
        l.add("A");
        l.add("B");
        l.add("C");
        l.add("D");
        l.add("E");
        ListIterator<String> iter = l.listIterator(l.size());
        while(iter.hasPrevious()){
            Object element = iter.previous();
            System.out.print(element + " ");
        }

结果是:

null E D C B A 

previous() 方法有什么问题,如何修复该问题,使其不会打印 null

protected Node<T> beginMarker;  // Dummy node marking the front of the list
protected Node<T> endMarker;    // Dummy node marking the back of the list
....................
public class AListIterator implements ListIterator<T>{
        protected Node<T> current;                
        protected Node<T> lastVisited = null;     
        protected int expectedModCount = modCount;
public boolean hasPrevious( ){
            if( expectedModCount != modCount )
                throw new ConcurrentModificationException( );

            return current != beginMarker;
        }

public T previous( ){
            if( expectedModCount != modCount )
                throw new ConcurrentModificationException( );
            if(!hasPrevious( ))
                throw new RuntimeException("Already at beginning of list"); 

            T prevItem = current.data;
            current = current.prev;
            return prevItem;
        } 

最佳答案

您不需要在两端都有虚拟标记。这是因为长度为 nListListIterator 仅具有 n + 1 个可能的光标位置(在每个位置之前) n 元素的集合,就在最后一个元素之后)。因此您只需要一个虚拟节点。

我会去掉 endMarker 并将其替换为对最后一个节点的引用。然后,当您调用 l.listIterator(l.size()) 时,您将得到一个迭代器,其中 current 最初是最后一个节点,因此您不会得到 null 在迭代开始时。

关于java - ListIterator 类的 Previous() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32983748/

相关文章:

java - 如何通过java获取ASPX文件的内容?

c - 如何使用 C 将值插入双向链表

java - 双向链表排序: One of the data display twice and the other one is missing

java - 将textview中的数字转换为int

java - 错误: org. xml.sax.SAXParseException : cvc-complex-type. 2.3

java - 可因式分解的三项式/多项式

c - 根据其内容从双向链表中删除结构(C 语言)

python - 从双向链表中删除节点并保持位置不变

c - 在双向链表中插入和删除元素

java - 如何向 Celltable ImageCell 添加点击处理程序?