public class A<E> extend AbstractList<E>{
private SLNode<E> Head = new SLNode<E>
private int length = 0; // length of the list
// I will skip the class of SLNode<E>
// Head's element and successor is initialized as null in the class SLNode<E>
public void add(int index, E element) // insert an element in the list
{
// if index is less than 0 or greater than the length
if( (index < 0) || (index > length ) )
throw new IndexOutOfBoundsException();
if(index ==0)
{
SLNode<E> newnode = new SLNode<E>(element, null); // make new node
newnode.setSuccessor(Head.getSuccessor());
Head.setSuccessor( newnode);
length++;
}
}
Q1. Is this right way of adding element at the front of the list? (using dummy header node, but no tail)
Q2. Would it be the same whether the list is empty or non-empty?
That’s not a bad way to do it, though using a “dummy” node for “head” is somewhat unusual.
But it has the advantage that you can replace “Head” with “current”, initialize that to “Head”, then “crawl” up the list
indexnodes and do your insert, and you wouldn’t have to special-case the zero case.(But note that standard naming convention is to reserve names with initial upper-case for class names.)