This repository has been archived by the owner on Aug 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path30-rimozione-di-elementi-duplicati-in-una-lista.cpp
105 lines (94 loc) · 1.92 KB
/
30-rimozione-di-elementi-duplicati-in-una-lista.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
* Author: Brian Ferri #0001040624
*
* Nome/Descrizione: 30-rimozione-di-elementi-duplicati-in-una-lista.cpp
*
* INF-UNIBO 2021-2022
* Primo anno del Corso di laurea in Informatica
*/
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
struct lista {
int val;
lista* next;
};
//Genera una lista contente numeri randomici da 0 a 50
lista* genera_elementi(int n) {
lista *aux, *head;
if(n < 1)
//cout << "Non e' stato possibile creare la lista, lunghezza inserita non valida!";
return NULL;
for(int i = 1; i <= n; i++) {
if(i == 1) {
head = new lista;
aux = head;
} else {
aux->next = new lista;
aux = aux->next;
}
aux->val = rand() % 50;
}
aux->next = NULL; //Aggiungo il NULL all'ultimo elemento
return(head);
}
//Stampa la lista
void stampa(lista* head) {
while(head != NULL) {
cout << head->val;
head = head->next;
if (head != NULL)
cout << ", ";
}
cout << endl;
}
void ins_coda(lista *head, int n) {
lista *tmp;
if (head == NULL) {
head = new lista;
head->val = n;
head->next = NULL;
} else {
tmp = head;
while (tmp->next != NULL)
tmp = tmp->next;
tmp->next = new lista;
tmp = tmp->next;
tmp->val = n;
tmp->next = NULL;
}
}
lista* dup(lista* head) {
lista* iter1 = head;
lista* iter2;
lista* nuova;
while (iter1 != NULL && iter1->next != NULL) {
iter2 = iter1;
while (iter2->next != NULL) {
if (iter1->val == iter2->next->val) {
nuova = iter2->next;
iter2->next = iter2->next->next;
delete nuova;
} else {
iter2 = iter2->next;
}
}
iter1 = iter1->next;
}
return head;
}
int main() {
srand(time(0));
lista *head;
int len;
cout << endl << "Quanto deve essere lunga la lista generata? ";
cin >> len;
cout << endl << "Numeri generati casualmente: " << endl;
head = genera_elementi(len);
stampa(head);
cout << "Lista senza duplicati: " << endl;
head = dup(head);
stampa(head);
cout << endl;
}