I am trying to remove duplicate elements from an unordered linked list in Java (a question from Cracking the Coding Interview).
I am using nested iterators over the same List object, but I get a ConcurrentModificationException
when I remove an item. This is my code:
Iterator<String> i = list.iterator();
String curr;
while (i.hasNext()) {
curr = i.next();
Iterator<String> j = list.iterator();
while (j.hasNext()) {
String runner = j.next();
if (curr == runner){
j.remove();
}
}
}
The solution in the book uses a LinkedListNode object, which makes it possible to just change the pointers of the nodes, but is there any way to solve this using java.util.LinkedList
only?
EDIT : The challenge was to do this without using a temporary buffer, otherwise an additional list would do the trick.