2
How to invert a simple chained list in Java? For example, I have the following values: 3 - 2 - 1 and the end result will have to be 1 - 2 - 3.
Note: no use of native Java functions such as Arraylist.
public void inverteLista() {
Lista atual = new Lista();
atual.setProx(primeiro);
for (int i = 0; i < tamanho; i++) {
atual = atual.getProx();
System.out.println(atual.getValor());
}
}
This code prints the list in normal order, however I do not know which logic used to reverse it.
take a read on Bubble Sort, then apply to java, there are examples ready in java on netna net. this is the easiest but not very efficient method for large lists.
– user23143
How is the algorithm and structure of the simple chained list? The inversion implementation may be dependent on this.
– Maniero
If in the original list the next of A is B, in the inverted list the next of B is A. If in the original list the next of the last is
null
, in the inverted list the next of the first isnull
. Based on this, you can invert it with a single pass (but the code is different if you want to modify the original list or if you want a new list - let us know if you need help with that). By the way, why are you doingLista atual = new Lista(); atual.setProx(primeiro);
? Why not justLista atual = primeiro;
, and pass theatual = atual.getProx()
for the end of the loop?– mgibsonbr
@mgibsonbr thanks for the explanation and the tip about the list, I had not thinking about this logic and I ended up doing by the longest method, I will update the code.
– Dan Lucio Prada