Remove duplicates in an unsorted Linked List
  • node
  • stackqueuelinkedlist
  • linkedlist
  • remove
  •   
  • Posted: 4 years ago
  • Edit
  • answers (1)
  • views (6178)

Write a function to remove duplicates from an unsorted Linked List.


Posted Answers

< Using additional buffer > We can use Hashtable to remove duplicates from a Linked List. Iterating through the list if the data at new node is found in the hashtable, remove that node.

public static void deleteDuplicate(LinkedListNode node){

Hashtable table = new Hashtable();
LinkedListNode previous = null;

while(node! = null){
if(table.containsKey(node.data))
previous.next = node.next;
else{
table.put(node.data, true);
previous = n;
}

node = node.next;
}
}


< Without using additional buffer >

public static void deleteDuplicate(LinkedListNode head){

if(head == null)
return;
LinkedListNode previous = head;
LinkedListNode current = previous.next;

while(current! = null){
LinkedListNode runner = head;
while(runner! = current){
if(runner.data == current.data){
/* Remove current */
LinkedListNode temp = current.next;
previous.next = temp;
current = temp;
break;
}
runner = runner.next;
}
if(runner == current){
previous = current;
current = current.next;
}
}
}

You need to Sign In to post your solution.