我制作了一个名为“add”的私有(private)递归方法,该方法应该递归地添加元素,但它不起作用。我知道java没有按引用传递,那么如何递归地添加元素呢?如果您能告诉我哪里错了,那就太好了。谢谢
public class linkedIt2 {
private int length = 0;
private Node head;
private class Node {
Node next;
int data;
public Node(int data, Node next) {
this.data = data;
this.next = next;
}
public Node(int data) {
this.data = data;
this.next = null;
}
}
public linkedIt2() {
head = null;
}
private void add(Node cur, int data) {
if (cur != null) {
add(cur.next, data);
} else {
cur = new Node(data, null);
}
}
public linkedIt2 insert(int data) {
add(this.head, data);
length++;
return this;
}
}
最佳答案
问题是,您无法更改引用。 cur.next 永远不会改变,因为引用是按值调用的。您需要在递归调用之前更改 cur.next。
您需要了解java“按值调用”的概念,没有按引用调用。引用作为值传输,因此更改引用参数本身,最初使用的对象不会发生任何变化。 也许: http://javadude.com/articles/passbyvalue.htm 使其更清晰。
一种解决方案:与您的类似:
最初,您必须确保 cur 不为空。然后您可以在函数内访问 cur.next 。如果为空,则结束递归,如果不为空,则继续深入。
private void add(Node cur, int data) {
if (cur.next != null) {
add(cur.next, data);
} else {
cur.next = new Node(data, null);
}
}
public linkedIt2 insert(int data) {
if (this.head == null) {
this.head = new Node(data, null);
} else {
add(this.head, data);
}
length++;
return this;
}
或者让 Node 进行递归并操纵自身。正如另一个解决方案所述。那就更好了。
关于java - 如何通过递归在链表中添加元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45359640/