当引用的节点值发生变化时,引用在链表中如何工作?

问题描述 投票:0回答:1

我想了解即使当前节点通过循环发生变化,临时值仍然引用第一个当前节点。感谢任何帮助。

  public class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }

  public static void main(String[] args) {
    
    ListNode temp = new ListNode(0) ;
    ListNode current = temp ;
   for(int i = 1; i <10 ; i++ ) {
       current.next = new ListNode(i) ;
       current = current.next ;
   }
    System.out.println(current.val); // output : 9
    System.out.println(temp.next.val); // output : 1
     System.out.println(temp.next.next.val); // output : 2
}

   }
java algorithm linked-list
1个回答
0
投票

当你这样做时,

 ListNode temp = new ListNode(0) ;
 ListNode current = temp ;

temp
current
只是对
ListNode
对象的两个引用,而不是对象(它们只是代表对象名称的别名)。
current
temp
现在指向同一个对象
ListNode(0)
。当你这样做时

current.next = new ListNode(i) ;
current = current.next ;

i
为 1 时,您可以将
next
中的引用
ListNode(0)
更改为通过
ListNode(1)
指向
current
(这不会更改或影响
temp
)。然后将
current
更改为指向
ListNode(1)
(这也不会更改或影响
temp
)。随着循环的继续,您可以对不同的
i
值重复相同的过程。

所以

temp
仍然没有改变,仍然指向
ListNode(0)
,因为你只是改变了
current
来指向不同的对象。

© www.soinside.com 2019 - 2024. All rights reserved.