I am curious as to what improvements to my code can be suggested.
package concepts;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class LinkedList<M> implements Iterable<LinkedListNode<M>> {
public static class LinkedListIterator<O> implements Iterator<LinkedListNode<O>> {
private LinkedListNode<O> curNode;
public LinkedListIterator(LinkedList<O> linkedList) {
curNode = linkedList.head;
}
@Override
public boolean hasNext() {
if (curNode != null) {
return true;
} else {
return false;
}
}
@Override
public LinkedListNode<O> next() {
if (!hasNext()) {
throw new NoSuchElementException();
} else {
LinkedListNode<O> temp = curNode;
curNode = curNode.next;
return temp;
}
}
}
public LinkedListNode<M> head;
public boolean add(M newData) {
LinkedListNode<M> newNode = new LinkedListNode<M>();
newNode.data = newData;
if (head == null) {
head = newNode;
} else {
LinkedListIterator<M> it = new LinkedListIterator<M>(this);
LinkedListNode<M> lastNode = null;
while (it.hasNext()) {
lastNode = it.next();
}
if (lastNode != null) {
lastNode.next = newNode;
} else {
throw new IllegalStateException();
}
}
return true;
}
@Override
public Iterator<LinkedListNode<M>> iterator() {
return new LinkedListIterator<M>(this);
}
}
Here is the LinkedListNode implementation:
package concepts;
public class LinkedListNode<N> {
public N data;
public LinkedListNode<N> next;
}