I am learning java and I am working with nodes, I want to create a method that returns the most used values in the list and how many times each one is used, however, when printing the values, the method does not return me exactly what I want
The code of the nodes
public class Nodo {
int x;
boolean empty;
Nodo next;
Nodo before;
public Nodo(int v)
{
// initialise instance variables
x = v;
next=null;
before = null;
}
public Nodo()
{
x = 0;
next=null;
before = null;
}
public int getVal(){
return x;
}
public void setNext(Nodo next)
{
this.next = next;
}
public void setBefore(Nodo before)
{
this.before = before;
}
}
One of the methods that insert a node and the method that should return the desired occurrence.
public class Lista {
Nodo cabeza;
Nodo cola;
Nodo siguiente;
Nodo anterior;
int dimension = 0;
List<Integer> list = new ArrayList<Integer>();
public Lista() {
cabeza=null;
cola=null;
}
public void addStart(int v) {
Nodo g = new Nodo(v);
if(cabeza == null) {
cabeza = g;
} else {
g.setNext(cabeza);
cabeza.setBefore(g);
cabeza = g;
}
dimension++;
list.add(0, v);
}
public void ocurrence() {
Nodo recorre = cabeza;
int array[] = new int [size()];
int contador = 0;
int frec = 1;
int valor = -1;
int frecuencia;
int modal = 0;
for(int i = 0 ;i < size(); i++) {
array[i] = recorre.getVal();
recorre = recorre.next;
}
for(int i = 0; i < array.length-1; i++) {
frecuencia = 1;
for(int j = i + 1; j < array.length; j++ ) {
if(array[i] == array[j])
frecuencia++;
}
for(int z = 0; z < array.length; z++) {
modal = frecuencia;
valor = array[i];
System.out.println("El elemento " + valor +
" se repite " + modal + " veces.");
}
}
}
From what I see the nodes are inserted well and seem to be linked, however, the problem is the impression itself, I guess the latter
for(int z = 0; z < array.length; z++) {
modal = frecuencia;
valor = array[i];
System.out.println("El elemento " + valor + " se repite " + modal + " veces.");
}
The method prints the values but prints a line of the result for each node or value in the list, for each value, instead of once per value.
I have tried several things but they have not worked for me, I do not know if it will be a very obvious logic error or I am completely lost.