How to remove a structure element

Asked

Viewed 889 times

0

I’m having trouble removing an item from the list. Follows code made:

#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");

}
  • 4

    And what’s the problem?

  • And why not just C++ and use std::list?

  • 3

    C++ or C ? They are very different things.

  • gives a look at this code https://github.com/brumazzi/pilha_stack/blob/master/stack.h

2 answers

0

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

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

But instead it’s like this:

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

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

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 didn’t understand why I created this pointer, I saw it used in the code) replacing it with * The problem is solved. Will be printed before and after exclusion normally:

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.