I am quite new to LinkedLists and was scratching my head as to how to tackle this problem:
"Write a piece of code that counts the number of duplicate elements in a linked list. That is, the number of elements whose values are repeated at an earlier index in the list. Assume that all duplicates in the list occur consecutively. For example, the list [1, 1, 3, 5, 5, 5, 5, 7, 7, 11] contains five duplicates: one duplicate of element value 1, three duplicates of element value 5, and one duplicate of element value 7."
Eventually, I came up with this answer:
//Initialization of variables and example elements
LinkedList<Integer> linkL = new LinkedList<Integer>();
int count = 0;
int currNum;
int compare;
linkL.add(11);
linkL.add(7);
linkL.add(7);
linkL.add(5);
linkL.add(5);
linkL.add(5);
linkL.add(5);
linkL.add(3);
linkL.add(1);
linkL.add(1);
Iterator<Integer> itr = linkL.iterator();
//Initalizes first two to compare.
currNum = itr.next();
System.out.println("curr num = " + currNum);
compare = itr.next();
System.out.println("curr num = " + compare);
//compares all elements in the list
while (itr.hasNext())
{
//if current element == next, advances the dupe count
if(currNum == compare)
{
howManyDupe++;
//advances the current element and fetches the next one
currNum = compare;
compare = itr.next();
}else //if not goes to the next set of elements
{
currNum = compare;
compare = itr.next();
}
}
//Gets the slopover
if(currNum == compare)
{
howManyDupe++;
System.out.println(howManyDupe + "duplicates in this list ");
}else
{
System.out.println(howManyDupe + " dupliates in this list ");
}
This code here works as described in the problem, but I wondered if anyone had any ideas of if there was a "better" way of doing it. Such as not using so many if statements, a better way to catch the slopover, a way of not having to initialize the first two elements, a way of writing it in fewer lines, etc. Please note: we were required to use the LinkedList class and not to create our own nodes and LinkedLists.