How to create simple circular chained list in C ?

Asked

Viewed 1,490 times

0

NOTE: The first element I am inserting outside of here, this is pro second from now, the while will run until the user type the id of a student -1 q ta in the create function. It’s falling in infinite loop!

void inserir(Aluno *aluno){

while(1){
    if(aluno->prox == NULL){
        Aluno *aux = aluno;
        Aluno *novo = criar();
        if(novo->id < 0)
            break;
        aux->prox = novo;
        novo->prox = aux;
    }else{

        Aluno *aux = aluno->prox;
        while(aux->prox != aluno){ // entra e um loop infinito
            printf("3\n");
            aux = aux->prox;

        }
        Aluno *novo = criar();
            if(novo->id < 0)
                break;  
            aux->prox=novo;
            novo->prox=aux; 
    }
}
}

1 answer

1


The simple circular list is defined by instead of the next of the last to port to null, points to the first of the list.

       Aluno *novo = criar();
        if(novo->id < 0)
            break;  
        aux->prox=novo;
        novo->prox=aux; 

You are creating a new knot, making it point to his previous one. No knot will point to student.

    Aluno *novo = criar();
        if(novo->id < 0)
            break;  
        aux->prox=novo;
        novo->prox=aluno; 

Now yes, aim for student and will not fall on loop.

  • thank you very much, it helped a lot

Browser other questions tagged

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