Turning a Simple List into a Double-Chained List

1

For a college job, I need to have a function in C receive a Simple List and return a Double-Chained List with the even numbers in the Simple List that was passed. My attempt is this, however it only displays the value '2'.

typedef struct lista{
    int info;
    struct lista* prox;
}Lista;

typedef struct listaDupla{
    int info;
    struct listaDupla* ant;
    struct listaDupla* prox;
}LD;

Lista* insereLista(Lista* l, int valor){
    Lista* novo = (Lista*)malloc(sizeof(Lista));
    novo->info = valor;
    novo->prox = l;
    return novo;
}
void imprimeLista(Lista* l){
    printf("---- lista -----\n");
    do{
        printf("%d\n", l->info);
        l= l->prox;
    }while(l != NULL);
}

LD* insereLD(LD* l, int valor){
    LD* novo = (LD*)malloc(sizeof(LD));
    novo->info = valor;
    novo->ant = l;
    novo->prox = NULL;
    if(l != NULL)
        l->ant = novo;
    return novo;
}

LD* modifica(Lista* l){
    LD* novo = (LD*)malloc(sizeof(LD));
    novo->ant = NULL,
    novo->prox = NULL;
    Lista* aux = l;
    while(aux != NULL){
        if((aux->info%2) == 0){
            novo = insereLD(novo, aux->info);
        }
        aux = aux->prox;
    }
    return novo;
}
void imprimeLD(LD* ListaDupla) {
    printf("\n---- lista dupla ----\n");
    while(ListaDupla != NULL){
        printf("%d\n", ListaDupla->info);
        ListaDupla = ListaDupla->prox;
    }
}

int main(){
    Lista* list = NULL;
    LD* listDup = NULL;

    list = insereLista(list, 1);
    list = insereLista(list, 2);
    list = insereLista(list, 4);
    list = insereLista(list, 89);
    list = insereLista(list, 88);

    imprimeLista(list);
    listDup = modifica(list);
    imprimeLD(listDup);
    return 0;   
}
    
asked by anonymous 11.04.2017 / 03:39

1 answer

0

There are only 2 fixes to be made:

1) The notes are reversed

LD* insereLD(LD* l, int valor){
    LD* novo = (LD*)malloc(sizeof(LD));
    novo->info = valor;
    /* ant e prox estão invertidos
    novo->ant = l;
    novo->prox = NULL;
    */
    novo->prox = l;
    novo->ant = NULL;
    if(l != NULL)
        l->ant = novo;
    return novo;
}

2) You are creating an LD without 'info', so it will create a position with the info set to a memory garbage. Starting LD with NULL only solves this problem

LD* modifica(Lista* l){
    /* Ira imprimir um lixo de memoria
    LD* novo = (LD*)malloc(sizeof(LD));
    novo->ant = NULL,
    novo->prox = NULL;
    */
    LD* novo = NULL;

    Lista* aux = l;
    while(aux != NULL){
        if((aux->info%2) == 0){
            novo = insereLD(novo, aux->info);
        }
        aux = aux->prox;
    }
    return novo;
}

The rest of the code is correct.

    
17.04.2017 / 22:46