2017-09-05 94 views
0

我有一個類:Java的傳球用listNode問題參考

class ListNode { 
    int val; 
    ListNode next; 
    ListNode(int x) { val = x; } 
} 

並打印LinkedList的功能是:

public static void printLinkedNode(ListNode l){ 
     while(l != null){ 
      System.out.print(l.val+" "); 
      l = l.next; 
     } 
     System.out.println(" "); 
    } 

在我的主要功能,創建一個名爲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); 

如果我做了:

ListNode fast = head, slow = head; 
fast = fast.next.next; 
printLinkedNode(head); // I get 1->2->3->4 

如果我B:

ListNode fast = head, slow = head; 
fast.next = fast.next.next; 
printLinkedNode(head); // I get 1->3->4 

我在爲什麼在A中,頭是1-> 2-> 3-> 4困惑,但不3-> 4?我看過一些帖子約Is Java 「pass-by-reference」 or 「pass-by-value」?,但仍無法弄清楚..

如果我這樣做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? 

我在爲什麼頭將改變迷茫的時候,我們做fast.next =新的ListNode(5);我認爲快速不是與頭部分配?

+0

'head'仍然引用同一個對象。在A中,讓'fast'引用與'head'相同的實例,然後將引用更改爲下一個節點,同時保持引用'head'不變。 Java是通過值傳遞的,因爲引用的「值」被複制並傳遞(不是引用的地址或指向引用的指針)。將Java引用看作是某種指針:'fast = head'意味着你有兩個指向相同地址的「指針」(它們具有相同的值),而當你執行'fast = xxx'時,你讓'fast'指向一些其他地址(你只改變那個指針的值)。 – Thomas

回答

3

當您將分配給變量時,您將它指向(引用)到特定對象。當你重新分配它,你讓點(參考)到另一個對象,你不會覆蓋它持有的參考值:

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 

相反,如果你做一些修改引用的對象,你」會編輯原始對象:

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 

更新的用例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 

爲了更容易理解:

比方說,我們有對象abListNode類型的c

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. 
+0

嗨,我編輯了我的問題並添加了一個案例,你能解釋一下C嗎?非常感謝。 – user6142261

+0

@ user6142261檢查我的更新。 – BackSlash