简体   繁体   中英

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:

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

Some Pictorial images for better illustrations

Here head, node1 and nextNode is an object

在此处输入图像描述

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

在此处输入图像描述

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

在此处输入图像描述

Hope it helps to comprehend!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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