簡體   English   中英

在Java中遍歷單鏈表

[英]traversing singly linked list in Java

我有一個簡單的Java問題。 如下面的代碼所示:

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;
    }

開始,快速和慢速尋址同一對象。 我不明白為什么“ slow = slow.next;” 不會更改起始對象,但是“ slow.next = slow.next.next;” 將更改起始對象。

slow是一個局部變量,因此更改其值以引用ListNode的新實例不會影響原始列表。

但是,如果slow是指ListNode屬於你的列表,改變slow.next指一個新的實例改變你的列表的狀態。

如果使用setter修改下一個節點,則可能會更清楚:

slow.next = slow.next.next;

相當於:

slow.setNext(slow.next.next);

因此,如果slow引用了屬於您列表的ListNode ,則更改其狀態即更改了列表的狀態。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM