我試圖編寫一個方法來刪除鏈接列表中的最後一個節點(用於學習如何修改鏈接列表..我沒有使用java庫LinkedList類)..我試圖處理與傳遞的鏈表只有一個節點的用例。使用java刪除鏈接列表中的節點
但是,當我嘗試在刪除前後打印鏈接列表時,它會提供相同的輸出,就像節點未被刪除一樣。
class NodeProcessing{
public static void removeLastNode(Node f){
if (f==null) return;
if(f.next == null){//if linkedlist has single node
f = null;
return;
}
...
}
public static void showList(Node first){
System.out.println("linked list=");
for(Node x = first; x != null; x = x.next){
System.out.print(x.item+" ,");
}
System.out.println();
}
public static void main(String[] args) {
Node a = new Node();
a.item = "one";
showList(a);
removeLastNode(a);
showList(a);
}
}
class Node{
String item;
Node next;
}
輸出:
鏈表= 一個,
鏈表= 一個,
更新: 當我使用的調試器,我可以看到Node a
在main()
有地址:[email protected]
和Node f
裏面的removeLastNode()
也有: [email protected]
您會發現,在您參考或按價值思考後,這是一個常見問題。當您在方法「removeLastNode」中設置節點空值時,它只是將複製引用「f」設置爲空,實際節點「a」總是指向實際值。順便說一下,您可以更改Node.item在你的Method.You可能會發現一些堆和堆棧的細節來尋找答案。 – Sstx