I have to make a linked list as a quasi-homework task, about which I have already asked two questions about here and here. Since the whole code is really big (400 lines approx.), I will include only the few functions I am asking you to review, although, if you need any more code, I will upload it.
Here is the .add(int, T)
function:
public void add(int index, T data){
if (getNode(index) == null){
throw new NoSuchElementException();
} else if (index<0 || index>=size){
throw new NullPointerException();
}
Node<T> crntNode;
Node<T> newNode = new Node<T>(data);
crntNode = getNode(index);
newNode.index = index;
if (crntNode.previousNode != null) {
crntNode.previousNode.nextNode = newNode;
} else {
firstNode = newNode;
}
crntNode.previousNode = newNode;
newNode.nextNode = crntNode;
crntNode = newNode;
while (crntNode.nextNode != null){
crntNode.index++;
crntNode = crntNode.nextNode;
}
size++;
}
The .get(int)
function:
public T get(int index){
if(isEmpty() || index < 0 || index >= size){
return null;
}
Node<T> crntNode;
int count = size - index - 1;
crntNode = lastNode;
while (count > 0) {
crntNode = crntNode.previousNode;
count--;
}
return crntNode.data;
}
And the .remove(int)
function:
public T remove(int index) {
if (getNode(index) == null || isEmpty()) {
return null;
} else if (size == 1){
size = 0;
Node<T> crntNode = firstNode;
firstNode = null;
lastNode = null;
return crntNode.data;
}
Node<T> crntNode = getNode(index);
if (crntNode.nextNode != null){
if (crntNode.previousNode != null){
crntNode.previousNode.nextNode = crntNode.nextNode;
} else {
firstNode = crntNode.nextNode;
firstNode.previousNode = null;
size--;
return crntNode.data;
}
}
if (crntNode.previousNode != null){
if (crntNode.nextNode != null) {
crntNode.nextNode.previousNode = crntNode.previousNode;
} else {
lastNode = crntNode.previousNode;
lastNode.nextNode = null;
size--;
return crntNode.data;
}
}
crntNode = crntNode.nextNode;
size--;
for(int i = index; i < size-1; i++){
crntNode = crntNode.nextNode;
crntNode.index--;
}
return crntNode.data;
}
I thought a lot about improving these functions, but I can't seem to find a better concept. The reason might be my lack of knowledge, in which case, I hope you could help me.
Is this code efficient and error-safe enough to be used in real programming situations?