我有一堂课:
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
Run Code Online (Sandbox Code Playgroud)
打印LinkedList的函数是:
public static void printLinkedNode(ListNode l){
while(l != null){
System.out.print(l.val+" ");
l = l.next;
}
System.out.println(" ");
}
Run Code Online (Sandbox Code Playgroud)
在我的主要功能中,我创建了一个名为test的ListNode:
ListNode test = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
Run Code Online (Sandbox Code Playgroud)
如果我做答:
ListNode fast = head, slow = head;
fast = fast.next.next;
printLinkedNode(head); // I get 1->2->3->4
Run Code Online (Sandbox Code Playgroud)
如果我做B:
ListNode fast = head, slow = head;
fast.next = fast.next.next;
printLinkedNode(head); // I get 1->3->4
Run Code Online (Sandbox Code Playgroud)
我很困惑,为什么在A中,头是1-> 2-> 3-> 4,而不是3-> 4?我已经阅读了一些有关Java是“按引用传递”还是“按值传递”的帖子?,但仍然无法解决。
如果我做C:
ListNode fast = head, slow = head;
fast = fast.next.next;
printLinkedNode(fast); //3->4
printLinkedNode(head); //1->2->3->4
fast.next = new ListNode(5);
printLinkedNode(fast); //3->5
printLinkedNode(head); //1->2->3->5, why the head will change?
Run Code Online (Sandbox Code Playgroud)
我困惑为什么我们做斋戒时头会改变。next= new ListNode(5); 我觉得快不配头吗?
当你分配一个变量,你让点(参考)特定对象。重新分配它时,使它指向(引用)另一个对象,不会覆盖它持有的引用值:
ListNode fast = head, slow = head; // fast has a reference to head.
fast = fast.next.next; // fast has a reference to fast.next.next. You are not overwriting head, just fast.
printLinkedNode(head); // I get 1->2->3->4
Run Code Online (Sandbox Code Playgroud)
相反,如果您在引用的对象内进行编辑,则将编辑原始对象:
ListNode fast = head, slow = head; // fast has a reference to head
fast.next = fast.next.next; // by editing fast.next, you edit head.next
printLinkedNode(head); // I get 1->3->4
Run Code Online (Sandbox Code Playgroud)
用例C的更新:
ListNode fast = head, slow = head; // fast = head = (1)
fast = fast.next.next; // fast = fast.next.next = (3). head is still (1)
printLinkedNode(fast); // 3->4 -> because fast points to head.next.next (3)
printLinkedNode(head); // 1->2->3->4 -> head wasn't modified by any of the previous instructions
// here fast points to head.next.next. So fast.next is the same as head.next.next.next (4).
fast.next = new ListNode(5); // Overwrites fast.next, it was (4), becomes (5)
printLinkedNode(fast); // 3->5
printLinkedNode(head); // 1->2->3->5
Run Code Online (Sandbox Code Playgroud)
为了更容易理解:
比方说,我们有对象a,b和c类型ListNode:
ListNode a = new ListNode(1);
ListNode b = new ListNode(2);
ListNode c = new ListNode(3);
ListNode d = a; // variable d now points to object a
d.next = b; // since d points to a, this statement modifies a.next
d = c // This does *not* modify a. It just makes d point to c.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
595 次 |
| 最近记录: |