Recursive Method LinkedList

2

I'm having difficulty implementing a recursive method for the method of inserting an element at the end of a simply linked list.

The following is the Iterative method:

public void addLast(Node<E> novoNodo){
    if(isEmpty())
        addFirst(novoNodo);
    else{
        novoNodo.setNext(null);
        tail.setNext(novoNodo);
        tail = novoNodo;
        size++;
    }
}

In the exercise I am trying to accomplish, I need to make this method into recursive, but I do not know how I can accomplish this, since the last method is not a looped method.

    
asked by anonymous 17.11.2014 / 17:14

1 answer

3

An example implementation for adding a recursively value to your simply linked list would be:

    private Node lista;

    public void addLast(int valor)
    {
        addLast(lista, valor);
    }

    private void addLast(Node lista, int valor)
    {
        if (lista == null)
        {
            this.lista = new Node(valor, null);
        }
        else
        {
            if (lista.getNext() == null)
            {
                lista.setNext(new Node(valor, null));
            }
            else
            {
                addLast(lista.getNext(), valor);
            }
        }
    }

First you need to have the initial node, and from there you begin to move to insert at the end of your list simply chained.

    
17.11.2014 / 17:51