Starting from 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:
The typedef
:
typedef struct Node node;
Makes it possible to use the name node
referring to
structure struct Node
making it easy to use in code.
Function vazia
:
int vazia(node *LISTA)
{
if(LISTA->prox == NULL)
return 1;
else
return 0;
}
Test only if the node received as parameter represents an empty list. This test is done by checking whether the next element received is null (NULL
) and returns 1
if it is. Note that this implementation will only work in a sentinel list. In a conventional list the empty list test is done by testing only if the first node is null.
Function aloca
:
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 attempts to allocate space to a new node using the function malloc
which returns a valid pointer if successful or NULL
otherwise. This is the reason for the if (!novo)
which checks if it was not possible to allocate and in this case gives a message and ends. If successful read the number to put on the node with scanf
and returns that node with return
.
Improving
All this logic could be improved and simplified, now look at 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 aloca
also can and should be improved by separating the logic of the list with the input of the data, but only with the code that is in the question is not possible to reformulate.
Don’t have a more specific question? Do you have to explain line by line? This code is not a good reference, it could be written much better.
– Maniero
Just what each block is able to do, does not need to be line by line
– Elder Son