这是我的代码,请仅引用主要方法和删除方法,其他方法只是为了显示完整的程序。我听说Java将方法参数作为按值传递,这就是问题所在,并且对象的属性是按引用传递。
所以基本上我可以更改Node.age
,因为age是一个属性,但我不能使Node
等于Node = Node.next
?我已经从事这个工作有一段时间了,只是想学习如何进行不同的操作,并且一直停留在这个问题上。 if 语句执行完毕,但是 headNode
并不像我希望的那样等同于 headNode.next
:
public class Node {
int age;
Node next;
Node previous;
public static void main (String [] args) {
Node firstNode = new Node(18);
Node t = firstNode;
Node randomFatNode = new Node();
for(int i = 0; i < 30; i += 3) {
Node tempNode = new Node(i + 21);
firstNode.next = tempNode;
tempNode.previous = firstNode;
firstNode = tempNode;
}
Node tailNode = firstNode;
firstNode = t;
traverseForward(firstNode);
//Prints out: Traversal Forward -> 18 -> 21 -> 24 -> 27 -> 30 -> 33 -> 36 -> 39 -> 42 -> 45 -> 48 -> null
deleteNode(firstNode, 18); //Does not delete the first node, which has the age of 18.
traverseForward(firstNode);
//Prints out: Traversal Forward -> 18 -> 21 -> 24 -> 27 -> 30 -> 33 -> 36 -> 39 -> 42 -> 45 -> 48 -> null
}
public Node() {
this.age = 20;
this.next = null;
this.previous = null;
}
public Node(int inputAge) {
this.age = inputAge;
this.next = null;
this.previous = null;
}
public static void traverseForward(Node headNode) {
System.out.print("Traversal Forward -> ");
Node useThisForTestNode = headNode;
while(useThisForTestNode != null) {
System.out.print(useThisForTestNode.age + " -> ");
useThisForTestNode = useThisForTestNode.next;
}
System.out.print("null ");
System.out.println();
}
public static void deleteNode(Node headNode, int keyToDelete) {
Node temp = headNode;
if(temp != null && temp.age == keyToDelete) {
headNode = headNode.next;
System.out.println("TEST");
//Printed out TEST to see if if statement went through. It did, but the node in the linked list remained unchanged.
}
}
// Other methods
}
最佳答案
您需要将firstNode作为类字段。
关于java - 我删除具有 X 年龄值的特定节点的删除方法将不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45778785/