0
I am in doubt in an exercise and if anyone could help me would be very good! Thanks from now!
#include <stdio.h>
#include <stdlib.h>
struct Numeros {
int numero;
struct Numeros *next;
};
void adicionar (int n, struct Numeros **here) {
struct Numeros *temporario;
if((*here)->next == NULL)
{getch();
(*here)->numero=n;
}
else if(((*here)->next->numero!=n)&&((*here)->next->numero>n))
{
temporario=(struct Numeros*)malloc(sizeof(struct Numeros));
temporario=(*here)->next;
temporario->numero=n;
temporario->next=(*here)->next;
(*here)->next=temporario;
free(temporario);
}
}
void remover (int n, struct Numeros **here) {
// 1- Verificar se não existem elementos na lista
// 1.1- sair
// 2- Caso exista elementos, verificar se o atual éo que se deseja remover
// 2.1- atualizar os ponteiros
// 3- Caso não seja o elemento procurado, avançar na lista procurando!
}
void imprimir (struct Numeros *here) {
printf("[%d]", here->numero);
if (here->next != NULL)
{
imprimir(here->next); // manda imprimir o proximo!
}
}
int main (){
struct Numeros *head = NULL;
int flag = 0, numero;
do {
printf("1) adicionar\n");
printf("2) remover\n");
printf("3) imprimir\n");
printf("0) sair\n");
printf("Informe uma opcao: ");
scanf("%d", &flag);
switch(flag){
case 0: // sair
break;
case 1: // adicionar
printf("--------------------------------------------\n");
printf("Informe o valor para ser adicionado: ");
scanf("%d", &numero);
adicionar(numero, &head);
printf("--------------------------------------------\n");
break;
case 2: // remover
printf("--------------------------------------------\n");
printf("Informe o valor para ser removido: ");
scanf("%d", &numero);
remover(numero, &head);
printf("--------------------------------------------\n");
break;
case 3: // imprimir
printf("--------------------------------------------\n");
(head != NULL) ? imprimir(head) : printf("Não existem elementos na lista\n");;
printf("\n");
printf("--------------------------------------------\n");
break;
default:
printf("Opcao invalida\n");
}
} while (flag);
free(head);
return 0;
}
In relation to
void remover(int n,struct Numeros **here)
do not need to worry because I have not yet started to develop or do, so I would like to have the opportunity to try, but my doubt is in adding, already from the
if((*here)->next == NULL)
begins to have flaws in the program. If someone can explain to me what is wrong and what is missing it would help me a lot in understanding. Thanks!!!
At first you have
head = NULL
when you access(* here)->next
or NULL->next, should give seg.fault. Maybe Juntat aif((*here) == NULL)...
– JJoao