I recently made a linked list for myself, the code of which was posted here, if anyone would be interested. Now, as the next task, I had to make an Iterator
for my list, which is working properly.
public Iterator<T> iterator() {
final MyLinkedList<T> list = this;
return new Iterator<T>() {
final Node<T> firstNode = list.firstNode;
Node<T> currentNode = null;
@Override
public boolean hasNext() {
if (list.isEmpty()) {
return false;
} else if (currentNode == null){
return true;
} else if (currentNode == list.lastNode){
return false;
}
return true;
}
@Override
public T next() {
if (list.isEmpty()){
throw new NoSuchElementException();
} else if (currentNode == null){
this.currentNode = firstNode;
return currentNode.data;
} else if (currentNode.nextNode == null) {
throw new NoSuchElementException();
}
this.currentNode = currentNode.nextNode;
return currentNode.data;
}
};
}
Here are the variables of the LinkedList
class:
private Node<T> lastNode;
private Node<T> firstNode;
private int size;
This is a Node<U>
:
private static class Node<U>{
private Node<U> nextNode = null;
private Node<U> previousNode = null;
private int index;
private U data;
private Node(U data){
this.data = data;
}
}
And this is how I add a new Node
:
public boolean add(T data) {
if (data == null) {
return false;
}
Node<T> currentNode = new Node<T>(data);
if (this.isEmpty()){
currentNode.previousNode = null;
currentNode.index = 0;
this.firstNode = currentNode;
} else {
currentNode.previousNode = lastNode;
lastNode.nextNode = currentNode;
currentNode.index = lastNode.index + 1;
}
this.lastNode = currentNode;
this.size++;
return true;
}
Could this be made significantly faster? Does the code comply with the Java coding conventions?
firstNode
field of the list, and it would help. \$\endgroup\$