Print chained list in C

Asked

Viewed 5,742 times

1

I’m creating a program that receives a vector and creates a chained list. I need help creating the "print()" function, which prints the generated chained list. I don’t know how to proceed.

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

// elemento da lista
typedef struct estr {

        int valor;

        struct estr *prox;

} NO;

NO* insereNoNaLista(NO* p, NO* lista){
    if(!lista) return p; //Se não houver nada na caixa de nós(lista = NULL), o ponteiro p aponta para NULL
    while(lista->prox != NULL ){ //"lista->prox = NULL" eh o ultimo elemento da lista
        lista = lista->prox; //Percorre os nós até que próximo elemento seja NULL
    }
    lista->prox = p; //Se lista->prox não for NULL, então o ponteiro p guarda o endereço de memoria do proximo elemento
    return lista; //devolve lista com todos os nos
}

//Recebe um vetor de inteiros e devolve uma lista ligada de nos
NO* deVetorParaLista(int *v, int t){
    int i;
    NO* p = NULL; 
    NO* lista = NULL; 

    for(i = 0; i < t; i++ ){
        p = malloc(sizeof(NO)); 
        p->valor = v[i]; 
        p->prox = NULL;
        lista = insereNoNaLista(p, lista); 
    }
    return lista;
}

void imprimir()

int main() {

    int v[] = {1,53,43,68,99, -7};
    int t = (sizeof(v))/sizeof(int); //tamanho do vetor v
    deVetorParaLista(v, t);

}

Another question: the functions inserts and fromVetorParaList return "list". How I could merge these two functions into a single one or utilize best programming practices?

  • You have to go through the Prox and print 'printf' the values you want

1 answer

5


A good programming practice would be to use more explanatory names for variables. In a small program like this it is not a problem, but in more complex programs it is better to use names that label minimally the purpose of the variable, especially if it is something more than a simple counter.

Another is to always free up memory when allocating dynamically. In general for each malloc there must be a free one. Again it would not be a problem in a small program and without repetitive allocation at the discretion of the user, and that does not use much memory as is the case for the kernel releases the memory as soon as the process is terminated. But it’s always good practice :) .

I took the liberty of following your suggestions and making a merged version of the first two functions and adding a memory wipe function.

Good luck in school.

// elemento da lista
typedef struct estr 
{

    int valor;
    struct estr *prox;

} NO;
//Recebe um vetor de inteiros e devolve uma lista ligada de nos
NO* deVetorParaLista(int *v, int t)
{
    int i;
    NO* p = NULL;
    NO* a = NULL;//endereco do no anterior
    NO* lista = NULL;

    for(i = 0; i < t; i++ )
    {
        p = (NO*)malloc(sizeof(NO));
        p->valor = v[i];
        p->prox = NULL;

        if(i==0)
        {
            //copia primeiro endereco para variavel a ser retornada
            lista=p;
        }else{
            //se nao for o primeiro elemento copia endereco para 'prox' do no anterior
            a->prox=p;
        }
        a=p;
    }
    return lista;
}

void imprimir(NO *p)
{
    printf("\n");
    while(p!=NULL)
    {
        printf("%d",p->valor);
        printf("\n");
        p=p->prox;
    }
}
//libera memoria alocada
void limparLista(NO *p)
{
    NO *n;
    while(p!=NULL)
    {
        n=p->prox;
        free(p);
        p=n;
    }
}

int main()
{

    int v[] = {5,17,-2,55,1000};
    int t = (sizeof(v))/sizeof(int); //tamanho do vetor v
    NO* p=deVetorParaLista(v, t);

    imprimir(p);

    //limpar lista(somente depois de usa-la)
    limparLista(p);

    return 0;
}
  • Thank you very much, Tsui! Can you explain to me the difference(concept) between the p pointer and the list? and why we cannot write "void print(NO *list)". From what I understand, the pointer points to a memory location, while the list acts as a "box" of nodes

  • 1

    The 'NO* list' variable is local to the'deVetorParaList(int*,int)' function. There are two variables 'NO* p' in this code, maybe this confused you, one of the 'clear' function (NO*), which receives the argument and another in 'main()'. We cannot write "void print(NO *list)" just because there is no variable with that name in the scope of 'main()'. All these variables receive nothing more than the address of the first element of the list through which it is accessed.

Browser other questions tagged

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