Linkedlist Recursive Method

Asked

Viewed 685 times

2

I’m having trouble implementing a recursive method for inserting an element at the end of a simply chained list.

Below 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’m trying to accomplish, I need to turn this method into recursive, but I don’t know how I can accomplish this, since the method last is not a method with ties.

  • 1

    It’s strange even that your addLast have no ties. Are sure that your implementation is correct? :)

1 answer

3


An example for implementation to add a value recursively in 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 it you start to scroll through to insert at the end of your simply chained list.

  • Hmmm understood, an auxiliary method would be the solution in the case!

  • Thanks for the help!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.