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);
}
}
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;
}
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...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.