How to remove a structure element

0

I'm having trouble removing an element from the list. Here is the code:

#include<stdio.h>// colocar no esquininho do AVA ate amanha
#include<stdlib.h>
#define max 5
typedef struct info
{
    int numero;
    struct info* prox;
}Lista; //tipo de dado

Lista* inicializar()
{
    return NULL;
}
Lista* inserir(Lista* prim,int valor)
{
    Lista* novo;
    novo=(Lista*)malloc(sizeof(Lista));
    novo->numero=valor;
    novo->prox=prim;

    return novo;
}
void Imprima(Lista* prim)
{
    while(prim!=NULL)
    {
        printf("\n%d\n",prim->numero);
        prim=prim->prox;
    }
}


Lista* retira(Lista* recebida, int v)
{
    Lista* ant=NULL;
    Lista* p=recebida;
    while(p!=NULL && p->numero!=v)
    {
         ant=p;
         p=p->prox;
    }
    if(p==NULL)

          return recebida;

          if(ant==NULL)
          {
            recebida=p->prox;
          }
          else
          {
               ant->prox=p->prox;

          }
          free(p);
        return recebida;
}
main()
{
    Lista* prim;
    Lista* p;
    int valor,resp,i,num;

    prim=(struct info*)malloc(sizeof(struct info));
    prim=inicializar();

    for(i=0;i<max;i++)
    {
        printf("\nDigite um valor: ");
        scanf("%d",&valor);
        prim=inserir(prim,valor);
        printf("\n\nGostaria de continuar 1 (sim) outro valor para nao: ");
        scanf("%d",&resp);

        if(resp!=1)
        {
            break;
        }

    }

    Imprima(prim);
    printf("Escolha um numero que queira remover: ");
    scanf("%d",&num);
    prim=retira(prim,num);
    Imprima(p);
    system("pause");

}
    
asked by anonymous 06.04.2016 / 20:08

2 answers

0

The problem is not in removal, but in printing the list after removal. I think you wanted to write:

p=retira(prim,num);
Imprima(p);

But instead it looks like this:

prim=retira(prim,num);
Imprima(p);

Then the list without the removed element is not being printed.

    
08.04.2016 / 02:12
0

A block of your code looks like this:

    Imprima(prim);
    printf("Escolha um numero que queira remover: ");
    scanf("%d", &num);
    prim = retira(prim, num);
    Imprima(p);
    system("pause");

The problem is in this pointer * p (I did not understand why I created this pointer, I did not use it in the code), changing it to * prim, the problem is solved. It will be printed before and after the deletion normally:

    Imprima(prim);
    printf("Escolha um numero que queira remover: ");
    scanf("%d", &num);
    prim = retira(prim, num);
    Imprima(prim);
    system("pause");

Possibly was giving error because your code was trying to print using a pointer that was not initialized.

    
16.05.2018 / 06:19