How to check if a data is already on my list

Asked

Viewed 31 times

-1

Well, I’m trying to do an activity, but I don’t understand the code very well, I would like to know how to check if a number is already on the list, as it is a new subject I’m half lost, as I should at least make the search function work ? the code I have so far.

#include<stdio.h>
#include<stdlib.h>

struct duplo{
    int num;
    struct duplo* ant;
    struct duplo* prox;
};

typedef struct duplo Duplo;

Duplo* criaListaNula(){
    return NULL;
}
Duplo* criaNo(){
    Duplo *novo = (Duplo*) malloc(sizeof(Duplo));
    return novo;
}

Duplo* insereInicio(Duplo* Cabeca, int dado){
    Duplo* novo = criaNo();
    novo->num = dado;
    novo->ant = NULL;
    if(Cabeca == NULL)
{
        Cabeca = novo;
        novo->prox = NULL;
        novo->ant = NULL;
    }else{
        novo->prox = Cabeca;
        Cabeca = novo;
    }
    return novo;
}
void imprime(Duplo* Cabeca)
{
    Duplo* aux = Cabeca;
    while(aux != NULL)
    {
        printf("%d ", aux->num);
        aux = aux->prox;
    }
}
int buscaDado(Duplo* Cabeca, int dado)
{
    Duplo *aux;
    for(aux = Cabeca; aux != NULL; aux = aux->prox)
        if((aux->num = dado))
        {
            return 1;
        }
    return 0;
}

int main()
{
    Duplo *Cabeca;
    int resp;

    Cabeca = criaListaNula();
    Cabeca = insereInicio(Cabeca, 5);
    Cabeca = insereInicio(Cabeca, 4);
    Cabeca = insereInicio(Cabeca, 7);
    Cabeca = removeInicio(Cabeca);

    resp = buscaDado(Cabeca, 4);
    if((resp=1))
    {
        printf("encontrado");
    }
    else
    {
        printf("nao encontrado");
    }
    return 0;
}

1 answer

0


You are doing assignment where you should be comparing (you are using = where you should use ==) in the following lines:

 if((aux->num = dado))

and

 if((resp=1))

In the latter if you do not need to compare with 1, any value other than 0 is evaluated as positive, you can stay only:

 if(resp)

Since you are assigning the returned value of the function to the head variable in main, its insertion function at the beginning can be simplified:

 Duplo* insereInicio(Duplo* Cabeca, int dado){
     Duplo* novo = criaNo();
     novo->num = dado;
     novo->ant = NULL;
     novo->prox = Cabeca; 
     return novo;
 }
  • It worked out bro, thanks mt, you know tell me how I would create two lists ? or if this code already creates 2, because it is double chained, I could not distinguish or understand how to create 2 lists in this code

  • Just declare another pointer to this other list: Duplo *Cabeca, *Cabeca2;

Browser other questions tagged

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