What is the function of this code snippet? Data structure (List)

0

I need to understand what each command is capable of doing, because it is without comments.

struct Node{
    int num;
    struct Node *prox;
};

typedef struct Node node;

int tam;

int vazia(node *LISTA)
{
    if(LISTA->prox == NULL)
        return 1;
    else
        return 0;
}

node *aloca()
{
    node *novo=(node *) malloc(sizeof(node));
    if(!novo){
        printf("Sem memoria disponivel!\n");
        exit(1);
    }else{
        printf("Novo elemento: ");
        scanf("%d", &novo->num);
        return novo;
    }
}
    
asked by anonymous 18.10.2017 / 16:54

1 answer

2

Starting at the beginning:

  • The structure:

    struct Node{
        int num;
        struct Node *prox;
    };
    

    This creates the structure for each node in the list, which will have a number and the pointer to the next node. Something that in memory will be represented as:

  • Otypedef:

    typedefstructNodenode;

    MakeitpossibletousethenamenodereferringtothestructurestructNodemakingiteasytouseincode.

  • Functionvazia:

    intvazia(node*LISTA){if(LISTA->prox==NULL)return1;elsereturn0;}

    Testsonlyifthenodereceivedasaparameterrepresentsanemptylist.Thistestisdoneverifyingthatthenextelementtothereceivedoneisnull(%with%)andreturns%with%ifitis.Notethatthisimplementationwillonlyworkonasentinellist.Inaconventionallisttheemptylisttestisdonebytestingonlyifthefirstnodeisnull.

  • FunctionNULL:

    node*aloca(){node*novo=(node*)malloc(sizeof(node));if(!novo){printf("Sem memoria disponivel!\n");
            exit(1);
        }else{
            printf("Novo elemento: ");
            scanf("%d", &novo->num);
           return novo;
       }
    }
    

    This function tries to allocate space for a new node using the 1 function that returns a valid pointer if successful or aloca otherwise. This is why malloc checks if it was not possible to allocate and in this case gives a message and ends. If successful it reads the number to be placed on the node with NULL and returns that node with if (!novo) .

Improving

All this logic could be improved and simplified, see an example:

typedef  struct Node{
    int num;
    struct Node *prox;
} node; //typedef ao mesmo tempo que declara a estrutura

int tam;

int vazia(node *LISTA)
{
    //assim contempla também o primeiro nó em si estar vazio
    return LISTA == NULL || LISTA->prox == NULL;
}

The scanf can also be improved by separating the logic from the list with the input of the data, but only with the code that is in the question it is not possible to reformulate.

    
18.10.2017 / 20:35