2
I’m trying to order a simple chained list, but I’m not succeeding, only changes the first node because the value is smaller, the rest does not change.
void ordenar(lista **l) {
int tam = tamanho((*l));
lista *prev, *current = (*l)->prox;
for(int i=0; i<tam - 1; i++) {
prev = *l;
for(int j=0; j<tam; j++) {
if(prev->data > current->data) {
troca(prev, current);
}
current = prev->prox;
}
prev = prev->prox;
}
}
why the second goes up to < pos - 1, and last element?
– túlio
Because Prev starts at the first element and Current at the second. If you do not place post-1, at the end of the for Prev will go to last element and Current will access an element that does not exist and cause error.
– Lucas Trigueiro
With the post-1 the Prev will go to the penultimate and Current to the last, making the exchanges normally.
– Lucas Trigueiro
ah, now I get it. I made a version without using the for. It became more readable. https://pastebin.com/1qXNb8ps
– túlio