Problem of printing a list because of repeated values

0

How can I do not to repeat a value in this list? Whenever I do something, I can not 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);

}
    
asked by anonymous 10.04.2016 / 05:54

1 answer

0

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

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 traverses your list by looking for whether the given value has already been entered.

In the insere method, change to:

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