嗨,夥計們我正在做一些與Java測試。如何設置已經實例化爲空的變量?
請參閱方法deleteMiddleNode()
,該方法假定給定節點,將其在鏈接列表中刪除。 這一切工作正常,除了我想刪除最後一個節點的情況。 我所做的是將最後一個節點設置爲null,如果這是要刪除的節點(請參閱評論)。它並不真正有效,並且s5
仍然有其價值。
當我只想重置s5
的屬性key
時,它確實有效。
我想知道爲什麼它的行爲如此。
public class Three {
static SinglyNode s5 = new SinglyNode(5);
public static void main(String[] args) {
SinglyNode s1 = new SinglyNode(1);
SinglyNode s2 = new SinglyNode(2);
SinglyNode s3 = new SinglyNode(3);
SinglyNode s4 = new SinglyNode(4);
s1.next = s2;
s2.next = s3;
s3.next = s4;
s4.next = s5;
deleteMiddleNode(s5);
SinglyNode ptr = s1;
while (ptr!= null) {
System.out.print(ptr.key+" ");
ptr = ptr.next;
}
}
// this method is wrong
public static boolean deleteMiddleNode(SinglyNode node){
if (node == null) {
return false;
}
if (node.next == null) { // last node
/* this part does work
System.out.println(node.key);
node.key = 222;
System.out.println(s5.key);
*/
node = null; // but this doesn't set the last node to null.
return true;
}
node.key = node.next.key;
node.next = node.next.next;
return true;
}
}
class SinglyNode {
int key = 0;
SinglyNode next = null;
public SinglyNode (int key){
this.key = key;
}
}
Java是*通過值*。您不改變方法之外的'node'參考值。 –
輕微,但重要的注意事項,如果它被設置爲「null」,它沒有被實例化。 –