I am attempting to create a custom Iterator on a LinkedList class I have made. I have been asked to alter the add function so that it adds objects Term in order from smallest to largest. (Term is a simple class taking the form Term(int power))
I cannot figure out how to create a loop in addTerm() in order to keep searching the next element to see if it is larger than the current power in Term. Can anyone help?
import java.util.Iterator;
public class customImpl implements custom{
private static class Node {
Term data;
Node next;
}
private Node head;
private class TermIterator implements Iterator<Term> {
private Node current;
private TermIterator(Node start) {
current = start;
}
@Override
public boolean hasNext() {
return current != null;
}
@Override
public Term next() {
Term result = current.data;
current = current.next;
return result;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Not supported");
}
}
/**
* Add a term to the expression
*
* @param term the term to be added.
*/
@Override
public void addTerm(Term term) {
TermIterator iterator = new TermIterator(head);
Node newNode = new Node();
while(iterator.hasNext()) {
if(term.getPower() > iterator.next().getPower()) {
newNode.next = head;
}
else newNode.data = term;
}
newNode.data = term;
newNode.next = head;
head = newNode;
}
/**
* Returns an iterator over elements of type {@code T}.
*
* @return an Iterator.
*/
@Override
public Iterator<Term> iterator() {
return new TermIterator(head);
}
}
addTermalready has a loop in it that does exactly what you're asking for. I think your problem resides within the iterator implementation.Iterator.next()should raiseNoSuchElementExceptionwhen past the end. Your implementation gets a generic null pointer.