How can I get the maximum value of a circular list that uses a sentinel node?
How can I get the maximum value of a circular list that uses a sentinel node?
Set a variable to contain the highest value starting with Long.MIN_VALUE
and scroll through the list from the sentinel element by element until you get back to the sentinel (or instead of Long.MIN_VALUE
, you can use the sentinel's own value). Whenever you find a value greater than what you have in that variable, you do the assignment.
Example without using Long.MIN_VALUE
when the value of the sentinel is usable. In this example, you do not even need a 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;
}
}