在Java中反转双链接列表而不创建新列表

在Java中反转双链接列表而不创建新列表,java,pointers,reverse,doubly-linked-list,Java,Pointers,Reverse,Doubly Linked List,我试图在Java中反转一个双链接列表,但似乎不明白为什么会出现空指针错误。我知道这里还有其他问题涉及同一主题,例如 还有我发现的其他一些 我很抱歉重复,但我认为我所做的与答案建议的是一样的,我似乎无法理解为什么我的功能不起作用 我知道我需要遍历列表,并将指针交换为next和previous,直到到达列表的末尾,这将导致列表反转 以下是我的函数代码: public void reverse() { Node<AnyType> temp = null;

我试图在Java中反转一个双链接列表,但似乎不明白为什么会出现空指针错误。我知道这里还有其他问题涉及同一主题,例如

还有我发现的其他一些

我很抱歉重复,但我认为我所做的与答案建议的是一样的,我似乎无法理解为什么我的功能不起作用

我知道我需要遍历列表,并将指针交换为next和previous,直到到达列表的末尾,这将导致列表反转

以下是我的函数代码:

    public void reverse() {

        Node<AnyType> temp = null;
        //Start at the beginning of the list
        Node<AnyType> current = beginMarker;
        //Go until the end of the list is reached
        while (current !=  null)
        {
            //Update temp to remember what came before the current node
            temp = current.prev;
            //Then switch the previous and next pointers
            current.prev = current.next;
            current.next = temp;  
            //Advance current to point to the next node in the list, which is now 
            //stored in current.prev           
            current = current.prev;
        }      
}

下面是关于调试我编写的java代码的小文章。听起来好像有帮助。简短版本:堆栈跟踪包含一些您想要的信息,您可以添加一些打印或使用调试器进行进一步调查。您忘记将新的头指针(循环中当前值的下一个但最后一个值)存储为新的列表指针。因此,main在试图打印反向字符串时遇到了一个NPE(这里猜一点点)。反向内部构件基本上正常。不是
void reverse
,而是
Node reverse
!好吧,它不会给你函数内部的错误,因为函数没有崩溃。要注意的单词是
next
,查看这一行以及一些打印可能会有所帮助。就像我说的,调查一下。我想@laune是对的,但是,为了将来。你想在按相反的顺序制作之后做什么?。。当您想使用arraylist时,可以按相反的顺序迭代它
Exception in thread "main" java.lang.NullPointerException
    at MyLinkedList$LinkedListIterator.next(MyLinkedList.java:285)
    at MyLinkedList.toString(MyLinkedList.java:186)
    at java.lang.String.valueOf(String.java:2847)
    at java.io.PrintStream.println(PrintStream.java:821)
    at MyLinkedList.main(MyLinkedList.java:321)