I am reviewing some snippets of code for an upcoming test. I saw this in my notes, and just now realized that this code for method 1 doesn't actually remove duplicates if the list is in this way A -> B -> C -> A. I wrote an alternative function (method 2) that I think will actually work. What do you guys think? Does method 1 actually not work, and I'm tracing it wrong? p.s. We are not allowed compilers at this time :)
Here is the code, and a short introduction of what it should do.
METHOD 1: What I think doesn't work when there are 2 exact things at the head and tail. Write code to remove duplicates from an unsorted list WITHOUT a buffer. Wwe can iterate with two pointers: “current” does a normal iteration, while “runner” iterates through all prior nodes to check for dups. Runner will only see one dup per node, because if there were multiple duplicates they would have been removed already.
public static void deleteDuplicates1(LinkedListNode head) {
if (head == null) return;
LinkedListNode previous = head;
LinkedListNode current = previous.next;
while (current != null) {
LinkedListNode runner = head;
while (runner != current) { // Check for earlier dups
if (runner.data == current.data) {
LinkedListNode tmp = current.next; // remove current
previous.next = tmp;
current = tmp; // update current to next node
break; // all other dups have already been removed
}
runner = runner.next;
}
if (runner == current) { // current not updated - update now
previous = current;
current = current.next;
}
}
}
I was thinking this would work. METHOD 2:
public void removeDuplicates2(){
Node current = null;
Node tracer = null;
for( current = head.next; current!=null; current=current.next){
for(tracer=head; tracer!=current; tracer=tracer.next){
if(tracer.data == current.data)
//DELETE THE NODE IN CURRENT
}
}
}