我做了一個名爲「add」的私有遞歸方法,它應該遞歸添加元素,但它不起作用。我知道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;
}
}
「不工作」是什麼意思? – OldProgrammer