RemoveListDuplicatedElements { public void remove(ListNode<Integer> head) { validateInput(head); Set<Integer> elements = new HashSet<Integer>(); ListNode<Integer> currentNode = head; ListNode<Integer> prevNode = null; while (currentNode != null) { if (elements.contains(currentNode.getData())) { prevNode.setNext(currentNode.getNext()); } else { elements.add(currentNode.getData()); } prevNode = currentNode; currentNode = currentNode.getNext(); } }  void remove(ListNode<Integer> head); void remove2(ListNode<Integer> head);  }
@Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNullInstancesAsParameter() { removeDuplicates.remove(null); }
@Test public void shouldNotModifyListIfThereAreNotDuplicatedElements() { ListNode<Integer> head = createList(new Integer[] { 0, 1, 2, 3, 4 }); removeDuplicates.remove(head); assertListContainsElements(new Integer[] { 0, 1, 2, 3, 4 }, head); }
@Test public void shouldRemoveDuplicatedElements() { ListNode<Integer> head = createList(new Integer[] { 0, 1, 0, 2, 2, 3, 4, 4 }); removeDuplicates.remove(head); assertListContainsElements(new Integer[] { 0, 1, 2, 3, 4 }, head); }