Reputation: 11
I am trying to recursively append an element to the end of a Linked List .However, Nothing seems to be added. I use a private helper method so I can use the reference as a parameter. I don't run into any exceptions, however, my test cases show that nothing at all has been added to the list! I have no idea what I'm doing wrong, and have no idea where to start. Your help is very appreciated.
public void addLast(E element) {
addLast(element,first);
}
private void addLast(E element, Node ref) {
if (ref == null) {
ref = new Node(element);
n++;
} else if (ref.next == null) {
ref.next = new Node(element);
n++;
} else {
addLast(element, ref.next);
}
}
Upvotes: 1
Views: 8144
Reputation: 755
You have to do something like this. Refer this link for explanation.
private Node addLast(E element, Node ref) {
if (ref == null) {
ref = new Node(element);
} else {
ref.next = addLast(element, ref.next);
}
return ref;
}
Upvotes: 6
Reputation: 9813
private void addLast(Node node){
while(root.next != null){
root = root.next;
if (root.next == null){
root.next = node;
break;
}
}
}
Not recursive because you don't need it...
Upvotes: 1