How to get the maximum value of a Java circular list?

Asked

Viewed 180 times

0

How can I get the maximum value of a circular list using a sentinel node?

1 answer

2


Set a variable to contain the highest value starting with Long.MIN_VALUE and go through the list from the sentinel element by element until you get back in the sentinel (or instead of Long.MIN_VALUE, you can use the sentinel value itself). Whenever you find a value greater than what is in this variable, you make the assignment.

Example without using Long.MIN_VALUE when the sentinel value is usable. In this example incidentally, you don’t even need sentinel:

public class No {
    private No proximo;
    private long valor;

    // getters, setters e outros métodos.

    public long maiorValor() {
        long maior = valor;
        for (No p = proximo; p != this; p = p.proximo) {
            if (p.valor > maior) maior = p.valor;
        }
        return maior;
    }
}

Example using Long.MIN_VALUE when the sentinel value is not usable:

public class No {
    private No proximo;
    private long valor; // Não deve ser usado se este nó for a sentinela.

    // getters, setters e outros métodos.
}

public class ListaCircular {
     private No sentinela;

    // getters, setters e outros métodos.

    public long maiorValor() {
        long maior = Long.MIN_VALUE;
        for (No p = sentinela.getProximo(); p != sentinela; p = p.getProximo()) {
            int v = p.getValor();
            if (v > maior) maior = v;
        }
        return maior;
    }
}
  • Would you have any example of code? I understood the explanation, but I’m not able to execute...

  • 1

    @Pedro Editado.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.