Comparison of equal elements and exclusion C++
I'm breaking my head to solve an exercise, I need to create a program that inserts elements into a chained list and then create a function to check if among the elements there are equal elements, and if so, delete all repetitions.
I don't know if I should use a recursive function for this, I tried to do a check with an auxiliary pointer, comparing each element with the rest, but I couldn't.
#include<iostream>
using namespace std;
struct no{
int n;
no *prox;
};
struct lista{
no *inicio;
};
int menu(){
int op;
cout << "\nl. Inserir na lista\n";
cout << "2. Remover da lista\n";
cout << "3. Imprimir lista\n";
cout << "4. Sair\n";
cout << "Opcao: ";
cin >> op;
return op;
}
no* criarNo(){
int num;
cout << "Qual numero quer inserir: ";
cin >> num;
no *novo = new no;
novo->n = num;
novo->prox = NULL;
return novo;
}
void inserirLista(lista *l){
no *insere = criarNo();
if(l->inicio == NULL){
l->inicio = insere;
}
else{
no *aux = l->inicio;
if(aux->n > insere->n){
insere->prox = l->inicio;
l->inicio = insere;
}else {
while(aux->prox != NULL && aux->prox->n < insere->n){
aux = aux->prox;
}
insere->prox = aux->prox;
aux->prox = insere;
}
}
}
void imprimirLista(lista *inicio){
if(inicio->inicio == NULL)
cout << "Lista vazia\n";
else{
no *aux = inicio->inicio;
while(aux->prox != NULL){
cout << aux->n << " ";
aux = aux->prox;
}
cout << aux->n << " ";
}
}
void removerRepetidos(lista *l){
/* while(aux->prox != NULL){
if(aux->n == aux->prox){
aux->prox = aux->prox->prox;
}
else()
}*/
}
int main(){
int opcao;
lista *l = new lista;
l->inicio = NULL;
while(true){
opcao = menu();
switch(opcao){
case 1:
inserirLista(l);
break;
case 2:
cout << "Remover numeros repetidos: ";
removerRepetidos(l);
break;
case 3:
imprimirLista(l);
break;
case 4:
return -1;
default:
cout << "Opcao invalida\n";
break;
}
}
return 0;
}
0
1 answers
You can use a set
to store the values of the nodes and if you find a value that already exists in this set you can eliminate the node. Remember to add the library #include <set>
void removerRepetidos(lista *l) {
set<int> elementos_passados;
no *atual = l->inicio;
no *anterior;
while(atual != NULL) {
if(elementos_passados.find(atual->n) != elementos_passados.end()) {
// esse elemento ja foi encontrado na lista
// delete o elemento atual
anterior->prox = atual->prox;
} else {
// adiciona o elemento no set
elementos_passados.insert(atual->n);
anterior = atual;
}
atual = atual->prox;
}
}
1
Author: André Luiz Bittencourt, 2019-11-22 15:36:40