0

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;
    }
}
Valerij Dobler
  • 1,848
  • 15
  • 25

1 Answers1

0

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;
    }
}
Valerij Dobler
  • 1,848
  • 15
  • 25
  • ahh i think I understand now! so basing off this, is this how the recursive remove method should be? 'private LLNode recRemove(LLNode node, T data) { if(node == null) { return null; } if(node.equals(data)) { LLNode newNode = new LLNode(data); head = newNode; newNode.setLink(node.getLink()); size--; return newNode; } return recRemove(node.getLink(), data); } @Override public boolean remove(T data) { return recRemove(head, data) != null; }' – hondacivic328 Sep 07 '20 at 21:37
  • I see multiple problems with your recRemove method. First one, `if (node.equals(data))` will never be true, because node and data are instances from different classes. And the second if you try to delete data from your list, you remove the old node, create a new node and place and chain the next nodes to it, yet you lose the connection to the previous node. – Valerij Dobler Sep 14 '20 at 12:44