英文:
Did i correctly implement the recursive add function? My front node is remaining null
问题
public class RecursiveLinkedCollection<T> implements CollectionInterface<T> {
LLNode<T> front;
int size = 0;
RecursiveLinkedCollection() {
front = null;
size = 0;
}
private LLNode<T> recAdd(LLNode<T> node, T data) {
if(node == null) {
LLNode<T> newNode = new LLNode<T>(data);
node = newNode;
}
if(node.getLink() == null) {
LLNode<T> newNode = new LLNode<T>(data);
node.setLink(newNode);
return newNode;
}
return recAdd(node.getLink(), data);
}
@Override
public boolean add(T data) {
recAdd(front, data);
return true;
}
}
英文:
I am supposed to implement a recursive linked list, but after writing the code and debugging, it seems that my front node is remaining unchanged (it is staying at null). Any help will be appreciated.
public class RecursiveLinkedCollection<T> implements CollectionInterface<T> {
LLNode<T> front;
int size = 0;
RecursiveLinkedCollection() {
front = null;
size = 0;
}
private LLNode<T> recAdd(LLNode<T> node, T data) {
if(node == null) {
LLNode<T> newNode = new LLNode<T>(data);
node = newNode;
}
if(node.getLink() == null) {
LLNode<T> newNode = new LLNode<T>(data);
node.setLink(newNode);
return newNode;
}
return recAdd(node.getLink(), data);
}
@Override
public boolean add(T data) {
recAdd(front, data);
return true;
}
}
答案1
得分: 0
根据您的add
方法,您试图从“front”节点添加新节点。在您的递归中,如果检查node
为null,则只有当“front”未设置时才会发生这种情况。您试图设置node = newNode
,但由于java始终是按值传递的,因此对front
的引用永远不会被设置。
public class RecursiveLinkedCollection<T> implements CollectionInterface<T> {
LLNode<T> head;
int size;
RecursiveLinkedCollection() {
}
private LLNode<T> recToTail(LLNode<T> next, T data) {
LLNode<T> newNode = new LLNode<T>(data);
if(next == null) {
head = newNode;
size++;
return head;
}
if(next.getLink() == null) {
next.setLink(newNode);
size++;
return newNode;
}
return recAdd(next.getLink(), data);
}
@Override
public boolean add(T data) {
return recAdd(head, data) != null;
}
}
英文:
According to your add
method, you try to append the new node from the front
-node. In your recursion if you check for node
being null, this can only happen if front
is not set. You try to set node = newNode
, but because java is always pass-by-value the reference to front
is never set.
public class RecursiveLinkedCollection<T> implements CollectionInterface<T> {
LLNode<T> head;
int size;
RecursiveLinkedCollection() {
}
private LLNode<T> recToTail(LLNode<T> next, T data) {
LLNode<T> newNode = new LLNode<T>(data);
if(next == null) {
head = newNode;
size++;
return head;
}
if(next.getLink() == null) {
next.setLink(newNode);
size++;
return newNode;
}
return recAdd(next.getLink(), data);
}
@Override
public boolean add(T data) {
return recAdd(head, data) != null;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论