0
In this C program, I’m trying to create a function that removes the first element of a chained dynamic list...
#include <stdio.h>
#include <stdlib.h>
struct no {
int dado;
struct no *prox;
};
The functions of the simply chained list I implemented are as follows::
Imprime Lista
void imprimir(struct no *prim){
struct no * atual;
atual = prim;
system("clear");
printf("\nLista: ");
while(atual != (struct no*)NULL)
{
printf("%d-> ",atual -> dado);
atual = atual -> prox;
}
}
Insert widget at start.
struct no * insere_inicio(struct no *prim){
int num;
struct no *novo;
printf("\nInsira o elemento no inicio da lista: ");
scanf("%d", &num);
novo = (struct no*) malloc(sizeof(struct no*));
novo -> dado = num;
novo -> prox = prim;
prim = novo;
return prim;
}
Remove element from start. Here is my problem, because instead of releasing memory and decrementing an element the function is just erasing the data from memory and returning the first node as 0 (zero).
Can anyone tell me what’s wrong?
All the rest of the code works.
struct no * remove_inicio(struct no *prim){
struct no *aux = prim;
if(prim == NULL){
printf("Lista Vaia!");
}
prim = prim -> prox;
free(aux);
return prim;
}
Insert element at end.
struct no * insere_final(struct no *prim){
int num;
struct no *novo;
struct no *atual;
printf("Insira o elemento no final da lista: ");
scanf("%d",&num);
novo = (struct no*) malloc(sizeof(struct no*));
novo -> dado = num;
novo -> prox = NULL;
atual = prim;
while(atual -> prox != NULL){
atual = atual -> prox;
}
atual -> prox = novo;
}
Remove element at the end.
struct no * remove_fim(struct no *prim){
struct no *atual = prim;
struct no *anterior;
if(prim == NULL){
printf("Lista Vaia!");
}
if(prim -> prox == NULL){
prim = NULL;
free(atual);
printf("Removido do final!");
}else{
while(atual -> prox != NULL){
anterior = atual;
atual = atual -> prox;
}
anterior -> prox = NULL;
free(atual);
printf("Removido do final!");
}
}
Function main
.
int main(){
int op;
struct no *prim;
prim = (struct no*) NULL;
do{
system("clear");
printf("\n<1> - Inserir no inicio");
printf("\n<2> - Inserir no final");
printf("\n<3> - Remover no inicio");
printf("\n<4> - Remover no final");
printf("\n<5> - Imprimir");
printf("\n<10> - Sair do programa\n\n");
printf("Digite sua opcao: ");
scanf("%d",&op);
switch (op)
{
case 1 : prim = insere_inicio(prim);
break;
case 2 : insere_final(prim);
break;
case 3 : remove_inicio(prim);
break;
case 4 : remove_fim(prim);
break;
case 5 : imprimir(prim);
break;
};
}while(op != 10);
return 0;
}
It is worth remembering that the use of pointer pointer facilitates life in other types of structures such as binary trees, when it is necessary to know who is the father of that element
– Andre Lacomski