简体   繁体   English

Java中反转链表混乱

[英]Reversing Linked List Confusion in Java

I'm having difficulty understanding a particular line of code when reversing a linked list in Java. Here is the method:在 Java 中反转链表时,我很难理解特定的代码行。方法如下:

public static ListNode reverseList(ListNode head)
{
    ListNode prev = null;

    while(head != null)
    {
        ListNode nextNode = head.next;
        head.next = prev;

        prev = head;
        head = nextNode;
    }

    return prev;
}

What I am having trouble with is the line head.next = prev;我遇到的麻烦是行head.next = prev; . . When this happens, I assumed that nextNode's value would also change because it also points to head.next.当发生这种情况时,我假设 nextNode 的值也会改变,因为它也指向 head.next。 However, it remained the same.然而,它仍然是一样的。 I know this has something to do with object references but I am not exactly sure.我知道这与 object 参考文献有关,但我不确定。

This confuses me because if I create 2 ListNode objects by pointing one to another likeso:这让我感到困惑,因为如果我通过将一个对象指向另一个对象来创建 2 个 ListNode 对象,就像这样:

    ListNode test = new ListNode(5);

    ListNode test2 = test;

and modify the 'test' object's val and print it out from 'test2', I get the same exact value likeso:并修改“test”对象的 val 并将其从“test2”打印出来,我得到了相同的精确值,如下所示:

    test.val = 8;

    System.out.println(test2.val); // this also prints out 8

Some Pictorial images for better illustrations一些图片以获得更好的插图

Here head, node1 and nextNode is an object这里head、node1和nextNode是一个object

在此处输入图像描述

As seen, headNext and nextNode is pointing to node1.如图所示,headNext 和 nextNode 指向 node1。 headNext is not an object but just referencing to node1. headNext不是 object 而只是引用 node1。

Next headNext is pointed to prev. next headNext指向prev。 Notice nextNode is still pointing to node1注意 nextNode 仍然指向 node1

在此处输入图像描述

For second example, after creating listNode test with value 5, test2 is assigned and pointed to test object. Hence any changes to test value will reflect to test2 too对于第二个示例,在创建值为 5 的 listNode test后,test2 被分配并指向测试 object。因此,对测试值的任何更改也会反映到 test2

在此处输入图像描述

Hope it helps to comprehend!希望对理解有所帮助!

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

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