Self-organizing List [closed]

1 day ago 1
ARTICLE AD BOX

We have classic nodes with a reference to the next Node, and a list having a head (last added element) and the last element holding no reference.

We have to implement the Frequency variant, which is supposed to order the list by how many times an element was accessed via calling the add/contains() method.

So if the list is 1, 2, 3, 4 with 1 being the head, and we call contains(3), the list changes its order to 3, 1, 2, 4, since 3 was called once and the other elements 0 times.

The project already implements methods for incrementing the frequency, the getter for it, a getHead() method and a getNext() method

public class SetFC<E> extends SetNaive<E> { public boolean contains2(final E element) { if (element == null) { return false; } Node<E> current = getHead(); Node<E> prev = null; while (current.getNext() != null) { // if the element is already at the beginning, no need to change anything if (current.equals(getHead())) { return true; } // element found if (current.getElement().equals(element)) { // increase the frequency of this element current.incFrequency(); // if current has no next, prev cant hold a reference to any element if (current.getNext() == null) { // set prev.next to null since its end of the list prev.setNext(null); // set current.next to (the previous) head of the list current.setNext(getHead()); // set current to be the new head setHead(current); } // the element is somewhere in the middle (start and end is handled) else { // link the previous element to the next prev.setNext(current.getNext()); // same procedure as before current.setNext(getHead()); setHead(current); } // reset prev to use it from the beginning prev = null; // now we prepared the arrangement by putting the found element at the start of the list. // we now need to swap it with its successor as long as its frequency is smaller than it // (and the next element is not null) while (current.getFrequency() < current.getNext().getFrequency() && current.getNext() != null) { // this part idk what to do, Im pretty sure the rest has errors too } return true; } prev = current; current = current.getNext(); } return false; } }

this method is always called by

public void add(final E element) { if (element == null) { throw new NullPointerException(); } else if (!contains(element)) { addToList(element); } }

in the Set<E> class (the variants inherit from SetNaive<E>, which is a subclass of Set<E>

What am I missing?

edit: In case you want to see, this was the while loop in a previous attempt:

while (current.getFrequency() < current.getNext().getFrequency()) { prev.setNext(current.getNext()); prev = current.getNext(); current.setNext(current.getNext().getNext()); prev.setNext(current); }
Read Entire Article