import java.util.*;
/*
* Remove duplicates from an unsorted linked list
*/
public class LinkedListNode {
public int data;
public LinkedListNode next;
public LinkedListNode(int data) {
this.data = data;
}
}
public class Task {
public static void deleteDups(LinkedListNode head){
Hashtable<Integer, Boolean> table=new Hashtable<Integer, Boolean>();
LinkedListNode previous=null;
//nth node is not null
while(head!=null){
//have duplicate
if(table.containsKey(head.data)){
//skip duplicate
previous.next=head.next;
}else{
//put the element into hashtable
table.put(head.data,true);
//move to the next element
previous=head;
}
//iterate
head=head.next;
}
}
public static void main (String args[]){
LinkedList<Integer> list=new LinkedList<Integer>();
list.addLast(1);
list.addLast(2);
list.addLast(3);
list.addLast(3);
list.addLast(3);
list.addLast(4);
list.addLast(4);
System.out.println(list);
LinkedListNode head=new LinkedListNode(list.getFirst());
Task.deleteDups(head);
System.out.println(list);
}
}
The result: [1, 2, 3, 3, 3, 4, 4] [1, 2, 3, 3, 3, 4, 4]
It does not eliminate the duplicates.
Why doesn't the method work?
Iterate through the linked list, adding each element to a hash table. When we discover a duplicate element, we remove the element and continue iterating. We can do this all in one pass since we are using a linked list.
The following solution takes O(n) time, n is the number of element in the linked list.
The first problem is that
does not actually initialize
head
with the contents oflist
.list.getFirst()
simply returns the Integer1
, andhead
contains1
as its only element. You would have to initializehead
by looping throughlist
in order to get all of the elements.In addition, although
modifies
head
, this leaveslist
completely unchanged—there is no reason why the changes tohead
should propagate tolist
. Therefore, to check your method, you would have to loop downhead
and print out each element, rather than printing outlist
again.All the solutions given above looks optimised but most of them defines custom Node as a part of solution. Here is a simple and practical solution using Java's LinkedList and HashSet which does not confine to use the preexisting libraries and methods.
Time Complexity : O(n)
Space Complexity: O(n)
This also preserves the list order.
It's simple way without HashSet or creation Node.
And to verify it:
The code below runs in O(1) space but O(N square) time.
public void deleteDups(LinkedListNode head){
}
Reference : Gayle laakmann mcdowell