Learn-dsa..in 30 days!



























CC-11 : Remove duplicates DoubleLinkedList.

Description:

Given a DoubleLinkedList with integer data, remove nodes that have duplicate data.

Test cases and expected outputs:

Input Parameters Expected outputs
63->97->96->32->53->97 63->96->32->53->97
88->77->77->66->33->55->77 88->66->33->55->77

Pseudocode:

Java.util.HashSet class can be used to check for duplicates. Create and instance of HashSet class called “uniqueValues” which accepts integer values.
Iterate the DoubleLinkedList from firstNode to end of the list. For each node, check if the data value already exists in the “uniqueValues” HashSet.
If the current node’s data value does not exist in the HashSet, add it to HashSet as a unique value.
Else, if the current node’s data value exists in the HashSet, we have found a duplicate, so currentNode can be removed from DoubleLinkedList.

Code:

public  void doubleLinkedListRemoveDuplicates(DoubleLinkedList doubleLinkedList) throws Exception{
	DoubleLinkedListNode currentNode=doubleLinkedList.getFirstNode();
	HashSet<Integer> uniqueDataValues=new HashSet<Integer>();
	do{
		if (uniqueDataValues.contains(currentNode.getNodeData())) {
			doubleLinkedList.remove(currentNode.getNodeData());
		}else {
			uniqueDataValues.add(currentNode.getNodeData());
		}
		currentNode=currentNode.getNextNode();					
	}while (currentNode!=null);
}

Click here to download and run code and test cases !