Question: Java: Find the mode of an already sorted linked list. I'm having issues with type compatibility. So, I want to get the mode, and return
Java: Find the mode of an already sorted linked list. I'm having issues with type compatibility. So, I want to get the mode, and return an object that implements a simple interface that has two methods (mode and count). Note: For some reason the "" isn't working properly on chegg so it doesn't show it is there but it is in the necessary places. I'm specifically having problems when I set: mode = (AnyType) current Here is my code along with the interface.
//find the mode of the list. Note that it is already sorted. public Result getMode() { int currCount = 0; LinkedListIterator itr = (LinkedListIterator) zeroth(); LinkedListIterator curr = (LinkedListIterator) first(); AnyType current = (AnyType) mode; while(curr.isValid()) { if(itr.retrieve().equals(curr.retrieve())) { currCount++; current = itr.retrieve(); } else if(!itr.retrieve().equals(curr.retrieve())) { if(maxCount < currCount) { maxCount = currCount; currCount = 0; mode = (AnyType) current; } } curr.advance(); itr.advance(); } return (Result) new Mode(); } private class Mode implements Result { public AnyType mode() { return mode; } public int count() { return maxCount; } } Here is the "Result" interface that I am implementing Mode from:
public interface Result { AnyType mode(); int count(); } NOTE: my mode variable was declared as a private data field in my class (which is basically a revision of the linked list class). I set mode initially equal to first().retrieve(); which is just taking the reference to the first node (not the header) and getting the value stored within that node. Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
