简体   繁体   English

在Java中遍历单链表

[英]traversing singly linked list in Java

I have a simple Java question. 我有一个简单的Java问题。 As shown in the below code: 如下面的代码所示:

public static ListNode removeNthFromEnd(ListNode head, int n) {

        ListNode start = new ListNode(0);
        ListNode slow = start, fast = start;
        slow.next = head;

        //Move fast in front so that the gap between slow and fast becomes n
        for(int i=1; i<=n+1; i++)   {
            fast = fast.next;
        }
        //Move fast to the end, maintaining the gap
        while(fast != null) {
            slow = slow.next;
            fast = fast.next;
        }
        //Skip the desired node
        slow.next = slow.next.next;
        return start.next;
    }

Start, fast and slow address the same object. 开始,快速和慢速寻址同一对象。 I don't get why "slow = slow.next;" 我不明白为什么“ slow = slow.next;” will not change the start object, but "slow.next = slow.next.next;" 不会更改起始对象,但是“ slow.next = slow.next.next;” will change the start object. 将更改起始对象。

slow is a local variable, so changing its value to refer to a new instance of ListNode doesn't affect the original list. slow是一个局部变量,因此更改其值以引用ListNode的新实例不会影响原始列表。

However, if slow refers to a ListNode that belongs to your list, changing slow.next to refer to a new instance changes the state of your list. 但是,如果slow是指ListNode属于你的列表,改变slow.next指一个新的实例改变你的列表的状态。

It may be clearer if you use a setter to modify the next node : 如果使用setter修改下一个节点,则可能会更清楚:

slow.next = slow.next.next;

would be equivalent to : 相当于:

slow.setNext(slow.next.next);

So if slow refers to a ListNode that belongs to your list, changing its state is changing the state of your list. 因此,如果slow引用了属于您列表的ListNode ,则更改其状态即更改了列表的状态。

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

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