List printing problem because of repeated values

Asked

Viewed 32 times

0

How can I not repeat a value on this list?
Every time I do something, I can’t print.

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;

typedef struct lista{
    int valor;
    struct lista *ponteiro;
}lista;    

lista *raiz=NULL;    

lista* insere( int valor){
    lista *aux=(lista*)malloc(sizeof(lista));
    aux->valor=valor;
    aux->ponteiro=raiz;
    raiz=aux;
    return raiz;
}

void imprime(lista* raiz){

    while(raiz!=NULL){
        cout<<"raiz: "<<raiz->valor<<"\n";
        raiz=raiz->ponteiro;
    }

}

int main(){
    void imprime(lista* raiz);
    lista* insere( int valor);
    int valor, op;
    do{
    cout<<"1- insere\n2-imprime\n3-zero para sair:";
    cin>>op;

    switch(op){

        case 1: cout<<"\ninsira um valor: ";
        cin>>valor;

        raiz=insere(valor );

        break;

        case 2: imprime(raiz);
        break;

        default:cout<<"valor errado ";
    }

}
    while(op!=0);

}
  • 1

    Sugestao: uses a C compiler for C programs, a C++ compiler for C++ programs. Using a C++ compiler for C programs (or vice versa) can, for example, create nonexistent errors or hide serious errors.

1 answer

0

Always before entering the value, you should check if it exists within your list.

To add the function n_exists:

char n_exists(int n){
    lista *swap = raiz;
    while(swap){
        if(swap->valor == n)
            return 1;
        swap = swap->ponteiro;
    }

    return 0;
}

This method goes through your list looking if a certain value has already been entered.

In the method insere, change to:

lista* insere( int valor){
    if(n_exists(valor)){
        puts("valor ja existente!");
        return raiz;
    }
    lista *aux=(lista*)malloc(sizeof(lista));
    /*...*/
}

Browser other questions tagged

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