2013-12-22 138 views
0

我想了解node1.next = node3node2 = node3之間的區別。 在鏈表中,node1.next = node3擺脫node2。但node1.next指向node2反正爲什麼node2 = node3不能在下面的代碼中工作?在java中單向鏈表中刪除一個節點

public class LinkedList { 
    LinkedList head = null; 
    LinkedList next = null; 
    int data = 0; 

    public static void main(String[] args) { 
     LinkedList node1 = new LinkedList(); 
     LinkedList node2 = new LinkedList(); 
     LinkedList node3 = new LinkedList(); 
     node1.data = 1; 
     node1.next = node2; 
     node2.data = 2; 
     node2.next = node3; 
     node3.data = 3; 
     node3.next = null; 

     node2 = node3;// If I replace with node1.next = node3; it works 
     LinkedList h = node1; 
     while (h.next != null) { 
      System.out.println(h.data); 
      h = h.next; 
     } 
    } 
} 
+6

與所有鏈接列表問題一樣,繪製包含框和箭頭的圖。然後你會明白。 –

+1

這可能會有幫助 - [是Java「通過引用」?](http://stackoverflow.com/q/40480)不是100%相同的問題,但非常接近。 – Dukeling

回答

0
node1 // points to a structure containing: 
    a 
    b 
    c 
    next --> node2 

node2 // points to a structure containing: 
    a 
    b 
    c 
    next --> node3 

node3 // points to a structure containing: 
    a 
    b 
    c 
    next --> <null> 

當您執行node2 = node3,你改變什麼,節點2變量指向。這不會改變node1中的任何內容。

當您執行node1.next = node3時,您將更改node1指向的next部分的內容。


在試圖使其100%清晰後,評論說這不是。

我們有三個變量,node1,node2和node3。其中的每一個駐留在某個特定地址的內存中,比如說10,20和30.

當一個對象被分配時,在特定地址有一個對應的內存塊;讓我們說節點1,節點2和節點3的對象已經分配了100,200和300的塊。

要說節點1「具有」它的對象的值,那麼在實現級別發生的是變量地址處的內存包含分配對象的地址。在我們的例子中,10的內存值爲100,20的值爲200,30的值爲300.

從100開始,由node1指向的內存塊中有一個字段,它包含指向另一個這樣的對象的指針;在我們的示例中,該字段的值爲200.

當我們執行node2 = node3時,我們會將值300放入內存地址20中.20中的內存現在包含300,它在其中包含300 200.但是,所有三個對象仍然存在,並且仍然可以到達,並且這個操作沒有改變。所以node1.next的值仍然是200。

我希望這可以100%清楚。如果沒有,請告訴我們,我記住的另一個例子是,我的網頁邊距太小,不能包含...

+0

仍然沒有100%清楚。 node2指向node3。爲什麼鏈表中的node2不會自動更新? – fidgetyPhil

+0

好的。感謝您的澄清。我想我終於明白了。想象3個房屋(物體)。 node1,node2,node3是三個地址卡。每個房子裏面都有一張名爲next的空白地址卡,告訴我們接下來要去哪個房子。當node1.next = node2時,我們將由node2表示的object2的位置複製到下一個地址卡上。後來,即使我們更改了node2上的地址,也沒關係,因爲我們已經將其上的原始地址複製到了node1.next – fidgetyPhil

+0

我必須記住索引卡 - 對於新手程序員來說可能比內存地址更好...如果你覺得它有用,你可以自由地投票選出這個以及任何其他答案,這是SO的工作方式。 – arcy

0

node1.next = node3node1.nextnode3,從而從列表中刪除node2

node2 = node 3node2node3;但是,node1.next仍然指向原始的node2(在它被重新分配爲指向node3之前),因此不會刪除node2

關鍵外賣如下:

node1.next = node2; 
node2 = null; 

System.out.println(node1.next.data); 
//prints whatever node2's data value was before becoming null 
0

執行代碼

node2 = node3; 

不會改變節點1的參考節點2或節點2的參考NODE3

僅此賦值語句改變存儲在變量node2處的內容

你這樣做之後,節點1仍然可以看到原來的節點2