I'm having trouble on how to start this method. I am trying to create a remove method using recursions in my code. Basically I have a public and private remove method. The remove(int) method, which is public, should remove the element at the specified index in the list. I need to address the case in which the list is empty and/or the removed element is the first in the list. If the index parameter is invalid, an IndexOutOfBoundsException should be thrown. To allow for a recursive implementation, this method should address special cases and delegate to remove(int, int, Node) for recursion.
Here's the class:
public class SortedLinkedList<E extends Comparable<E>>
{
private Node first;
private int size;
// ...
}
And here's the code:
public void remove(int index)
{
if(index < 0 || index > size)
{
throw new IndexOutOfBoundsException();
}
remove(index++, 0, first);
if (index == 0)
{
if(size == 1)
{
first = null;
}
else
{
first = first.next;
}
}
size--;
}
And the private method:
private void remove(int index, int currentIndex, Node n)
{
if(index == currentIndex)
{
remove(index, currentIndex, n.next);
}
remove(index, currentIndex, n.next.next);
}
With a private class:
private class Node
{
private E data;
private Node next;
public Node(E data, Node next)
{
this.data = data;
this.next = next;
}
}