Search code examples
javado-whilecircular-list

How to count duplicates in a list using a circular linked list


I am working on expanding my circular linked list and I implemented a few methods that will add and delete nodes from a list. I want to create a method that will count the duplicates in a list, the method should return the number of objects that occur more than once in the list. for example a list has [30, 30, 50, 50, 80, 90, 10, 10] the method should return: the number of duplicates is 3

I have tried implementing the following method but this method only counts the total nodes in the list, what should I add to make it count the duplicates in the list.

public int countNode() {
    int count = 0;

    if (!isEmpty()) {
        Node<E> temp = current;
        Node<E> prev = current;

        do {
            if (prev.element == temp.element)
                count++;
                temp = temp.next;
                prev = prev.next;
        } while (temp != current);
    }

    return count;
}

Solution

  • The simple solution is to use Java's HashSet data structure which only allows unique values. You will need to add each node's value to the set as you iterate. In the end, the difference between the size of the set and the size of the list will be your answer.

    Here I've simplified an example code by representing circular linked list as an array of integers:

    // Your linkedlist, shown as an array
    int[] arr = new int[] {30, 30, 50, 50, 80, 90, 10, 10};
    
    // Allows only unique values
    HashSet<Integer> set = new HashSet<Integer>();
    
    // Fill your set
    for(int n : arr) {
        set.add(n);
    }
    
    // answer = list's length - set's length
    System.out.println(arr.length - set.size());