反转链表的困惑在Java中

huangapple go评论60阅读模式
英文:

Reversing Linked List Confusion in Java

问题

我在反转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;
}

我遇到困难的是这行代码 head.next = prev;。当这个操作发生时,我以为 nextNode 的值也会改变,因为它也指向 head.next。然而,它的值保持不变。我知道这与对象引用有关,但我不太确定。

这让我困惑,因为如果我创建两个 ListNode 对象,一个指向另一个,像这样:

ListNode test = new ListNode(5);

ListNode test2 = test;

然后修改 test 对象的值并从 test2 打印出来,我会得到完全相同的值,如下所示:

test.val = 8;

System.out.println(test2.val); // 这也会打印出 8
英文:

I'm having difficulty understanding a particular line of code when reversing a linked list in Java. Here is the method:

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;. When this happens, I assumed that nextNode's value would also change because it also points to head.next. However, it remained the same. I know this has something to do with object references but I am not exactly sure.

This confuses me because if I create 2 ListNode objects by pointing one to another likeso:

    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 = 8;

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

答案1

得分: 1

以下是要翻译的内容:

一些图示图像,以更好地说明

这里,head、node1和nextNode都是对象

如图所示,headNext和nextNode指向node1。headNext不是对象,只是引用node1。

接下来,headNext指向prev。请注意,nextNode仍然指向node1。

对于第二个示例,在创建具有值5的listNode test之后,将test2分配并指向test对象。因此,对test值的任何更改也将反映在test2上。

希望这有助于理解!

英文:

Some Pictorial images for better illustrations

Here head, node1 and nextNode is an object

反转链表的困惑在Java中

As seen, headNext and nextNode is pointing to node1. headNext is not an object but just referencing to node1.

Next headNext is pointed to prev. Notice nextNode is still pointing to node1

反转链表的困惑在Java中

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

反转链表的困惑在Java中

Hope it helps to comprehend!

huangapple
  • 本文由 发表于 2020年8月3日 01:45:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/63219245.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定