Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 不在双链接列表中插入节点_Java_Linked List_Nodes_Doubly Linked List - Fatal编程技术网

Java 不在双链接列表中插入节点

Java 不在双链接列表中插入节点,java,linked-list,nodes,doubly-linked-list,Java,Linked List,Nodes,Doubly Linked List,在add方法中,我必须插入一个节点,但代码恰好没有将该节点添加到列表中。add方法与迭代器一起工作,将具有指定数据的节点添加到元素之前的列表中,该元素将通过调用next返回。 例如: SimpleList<String> list = new SimpleList<String>(); list.add("A"); list.add("B"); list.add("C"); list.add("D"); list.add("E")

在add方法中,我必须插入一个节点,但代码恰好没有将该节点添加到列表中。add方法与迭代器一起工作,将具有指定数据的节点添加到元素之前的列表中,该元素将通过调用next返回。 例如:

 SimpleList<String> list = new SimpleList<String>();
    list.add("A");
    list.add("B");
    list.add("C");
    list.add("D");
    list.add("E");
    System.out.println(l); // Output is [A,B,C,D,E]

    ListIterator<String> iter = list.listIterator();
    iter.add("1th");
    System.out.println(l);

不是答案,只是一个注释:我想,如果列表为空,add方法不应该抛出异常。将项目添加到空列表是可以的。您正在创建一个新节点并设置其下一个和上一个指针,但忘记更改该节点周围节点的下一个和上一个指针。请注意,根据javadoc,新节点应插入next返回的元素之前。@JBNizet So,lastVisited.next=newNode;current.prev=newNode;应该有用。但是,此代码将在当前项之前插入新项,而预期它将在当前项之后插入。此外,它将使迭代器向前移动一步-这是不明显的,可能会混淆开发者\用户。@JBNizet,我仍然有问题。我更改了代码并链接了环境:lastVisited.next=newNode;newNode.prev=上次访问;newNode.next=当前;current.prev=newNode;但仍然无法达到预期的效果。你能再看一次这个评论中的代码吗?
public class AListIterator implements ListIterator<T>{
        protected Node<T> current;                 // Current node, return data on call to next()
        protected Node<T> lastVisited = null;      // Used for calls to remove
        protected boolean lastMoveWasPrev = false; // Necessary for implementing previous()
        // Move the iterator forward and return the passed-over element
        public T next( ){
            if(!hasNext( ))
                throw new RuntimeException("Already at end of list"); 
            T nextItem = current.data;
            lastVisited = current;
            current = current.next;
            lastMoveWasPrev = false;
            return nextItem;
        }
public void add(T x){
            this.next();
            Node<T> newNode = new Node<T>(x);
            newNode.prev = lastVisited;
            newNode.next = current;
        }