有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

Reversing a Doubly Linked List

Reversing a linked list

还有我发现的其他一些

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

我知道我需要遍历列表,并将指针交换为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;
        }      
}

这就是我想我正在做的:

当我进行交换时,创建一个临时变量来保存上一个值的下一个值,最初设置为null,因为最后一个节点应该有一个指向null的指针。接下来是一个当前变量,用于保存我当前在列表中的位置

当current不为null时,所以当我不在列表的末尾时,我将temp变量设置为current之前的值。然后,我将指针交换为上一个和下一个,并将current的新值设置为current.prev,这将使我在列表中向前移动一个节点

然而,这里一定有我遗漏的东西。我希望能被推向正确的方向

编辑: 这是我的堆栈跟踪,但它没有给我函数中的错误,因此我不确定如何准确地读取它以找到问题所在

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)

共 (0) 个答案