In this program in C, I'm trying to create a function that removes the first element from a linked dynamic list ...
#include <stdio.h>
#include <stdlib.h>
struct no {
int dado;
struct no *prox;
};
The functions of the simply linked list that I have implemented are as follows:
Print List
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 element at the beginning.
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 the beginning. Here is my problem, because instead of releasing memory and decrementing an element the function is just deleting the data from memory and returning the first node as 0 (zero).
Does anyone know what's wrong?
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;
}