1

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);
    }
}
2
  • First of all, what is n? Is your problem that the list is always empty? If yes, then try changing 'ref = new Node(element)' under the first if block to first = new Node(element), where 'first' is your list's head pointer. Commented Nov 2, 2013 at 3:20
  • Could you please post an example that results in an empty LinkedList? Commented Nov 2, 2013 at 3:23

2 Answers 2

6

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1
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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.