Skip to content
Advertisement

Did i correctly implement the recursive add function? My front node is remaining null

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;
    }
}

Advertisement

Answer

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;
    }
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement