Double linked list in C

Asked

Viewed 94 times

0

Hello, I can’t understand what’s wrong with the code below. It was to add an element at the end of the linked list, but nothing happens and everything compiles without errors.

Can someone help me, please?

struct cel {
    int info;
    apontador prox;
    apontador ant;
};

typedef struct cel * apontador;


void insereNoFim(int x, apontador lista) {
    apontador aux = lista;

    if (lista == NULL) {
        lista = malloc(sizeof(struct cel));
        lista->info = x;
        lista->ant = lista->prox = NULL;
    }
    else {
        while (aux->prox != NULL) {
            aux = aux->prox;
        }
        aux->prox = malloc(sizeof(struct cel));
        aux->prox->info = x;
        aux->prox->ant = aux;
        aux->prox->prox = NULL;
    }  
}
  • how so "nothing happens" ? what was to "happen" and not "happened" ? your question is very inaccurate

1 answer

0

The problem is that the function insereNoFim takes the parameter lista as a value and not as a reference (even if the type apontador is a pointer). You could receive the parameter lista as a pointer to apontador:

void insereNoFim(int x, apontador *lista) {
    apontador aux = *lista;

    if (*lista == NULL) {
        *lista = malloc(sizeof(struct cel));
        (*lista)->info = x;
        (*lista)->ant = lista->prox = NULL;
    }
    else {
    ...

Or could create a function to initialize a list, while the function insereNoFim would only insert values themselves:

apontador iniciarLista(int x){
    apontador lista = malloc(sizeof(struct cel));
    lista->info = x;
    lista->ant = lista->prox = NULL;
}

int insereNoFim(int x, apontador lista) {
    apontador aux = lista;

    if (lista == NULL) {
        return 0;
    }
    else {
        ...
        return 1;
    }  
}

Another possibility would be to create a new type, which would be a structure containing a apontador, for example:

typedef struct lista{
    apontador inicio;
}*lista;

Thus, the boot function would be:

lista iniciarLista(void){
    lista novaLista = malloc(sizeof(struct lista));
    novaLista->inicio = NULL;
}

The function insereNoFim would be as follows:

int insereNoFim(int x, lista _lista) {
    apontador aux;
    if(_lista == NULL){
        return 0;
    }
    aux = _lista->inicio;

    if (aux == NULL) {
        _lista->inicio = malloc(sizeof(struct cel));
        _lista->inicio->info = x;
        _lista->inicio->ant = lista->prox = NULL;
    }
    ...
    return 1;
}

Browser other questions tagged

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