A Single-Linked List Class
Add a node to the front of the list:
private void addFirst (E item) {
head = new Node<E>(item, head);
size++;
}
Add a node after another node:
Click HERE for the code.
private
void addAfter (Node<E> node, E item) {
node.next = new Node<E>(item, node.next);
size++;
}
private Node<E> getNode(int index) {
Node<E> node = head;
for (int i=0; i<index && node != null; i++) {
node = node.next;
}
return node;
}
public void add (int index, E item) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException(Integer.toString(index));
}
if (index == 0) {
addFirst(item);
} else {
Node<E> node = getNode(index-1);
addAfter(node, item);
}
}
To add an item to the end of the list:
public boolean add (E item) {
add(size, item);
return true;
}