I am lost and really hope someone could help me out here, I am supposed to create a function that finds duplicated number nodes and delete the duplicates. Whenever I run the whole code I am stuck in an infinite loop inside while(current.next != null).
My main question is, I know my problem resides in if (tester.data == current.data). I do not understand why they never test or compare (their ints). I am sorry if this is a vague question I have been staring at my screen baffled for hours.
public void removeDuplicate()
{
// removes all duplicate nodes from the list
Node tester = head;
Node previous = head;
Node current = head.next;
while (tester.next != null){
int i = 0;
while(current.next != null){
System.out.println("Stuck here3");
if (tester.data == current.data){
Node tempNode = current.next;
previous.next = tempNode;
current = tempNode;
size--;
System.out.println("Stuck here2");
break;
}
else{
previous = current;
current = current.next;
}
}
System.out.println("Stuck here1");
tester = tester.next;
current = tester.next;
}
}
No, that’s not your problem. They do in fact test and compare, and the deletion of the node works when that happens.
There are, however, other problems in your code.
Because of the
breakin the inner loop, you only remove one duplicate for each value.If you remove that
breakit gets closer, but at the end of the loop, you haveand you don’t set
previousto an appropriate new value.It should be
With both these changes made, your code deletes all duplicates except if one occurs at the very end of the list.
I suspect I could fix that as well, but I’m more inclined to do pretty much a complete rewrite. If I do, I may post it.