I'm currently trying to brush up on ADT implementations, specifically an implementation for a Linked List (I'm using Java 5 to do this).
Is this implementation I've written for add(i, x) correct and efficient?
public void add(int i, Object x) {
// Possible Cases:
//
// 1. The list is non-empty, but the requested index is out of
// range (it must be from 0 to size(), inclusive)
//
// 2. The list itself is empty, which will only work if i = 0
//
// This implementation of add(i, x) relies on finding the node just before
// the requested index i.
// These will be used to traverse the list
Node currentNode = head;
int indexCounter = 0;
// This will be used to mark the node before the requested index node
int targetIndex = i - 1;
// This is the new node to be inserted in the list
Node newNode = new Node(x);
if (currentNode != null) {
while (indexCounter < targetIndex && currentNode.getNext() != null) {
indexCounter++;
currentNode = currentNode.getNext();
}
if (indexCounter == targetIndex) {
newNode.setNext(currentNode.getNext());
currentNode.setNext(newNode);
} else if (i == 0) {
newNode.setNext(head);
head = newNode;
}
} else if (i == 0) {
head = newNode;
}
}