0

I need to write a method that inserts items into a singly linked sorted list recursively. The node class for the list looks like this:

protected class Node<T> {

    protected Node(T data) {
        this.data = data;
    }

    protected T data;
    protected Node<T> next;
}

protected Node<E> head;

}

The method signature is: void insert(E data). I can do this iteratively but I just can't seem to wrap my head around how to do it recursively. Can anyone offer any insight?

2 Answers2

1

Assuming you're supposed to be inserting at the end of the list, just recur on this.next until this.next is null.

public void insert(E data) {
    if (this.next == null) {
        // we're at the end, so actually do the insert
        // if you can do it iteratively, you should already know what to do here
    } else {
        this.next.insert(data);
    }
}
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
0

Create a function that takes a starting node and the data to insert.

If that node is the right place to put the data, just insert it.

If not, call the function recursively to try the next node.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964