fork download
  1. #include <iostream>
  2. #include <unordered_set>
  3. using namespace std;
  4.  
  5. struct List {
  6. int data = 0;
  7. List* next = nullptr;
  8. List(int x) : data(x) {}
  9. };
  10.  
  11. void remove_duplicates(List* head) {
  12. std::unordered_set<int> cache;
  13. cache.insert(head->data);
  14. List* next = head->next;
  15. while (next != nullptr) {
  16. if (cache.count(next->data) > 0) {
  17. head->next = next->next;
  18. delete next;
  19. next = head->next;
  20. } else {
  21. cache.insert(next->data);
  22. head = next;
  23. next = head->next;
  24. }
  25. }
  26. }
  27.  
  28. int main() {
  29. List* head = new List(1);
  30. List* list = head;
  31. for (int index = 2; index < 10; ++index) {
  32. List* next = new List(index);
  33. if (next->data % 2 == 0) {
  34. next->data = 2;
  35. } else if (next->data % 3 == 0) {
  36. next->data = 3;
  37. }
  38. list->next = next;
  39. list = next;
  40. }
  41.  
  42. remove_duplicates(head);
  43.  
  44. while (head != nullptr) {
  45. printf("%d\n", head->data);
  46. head = head->next;
  47. }
  48.  
  49. return 0;
  50. }
Success #stdin #stdout 0s 4340KB
stdin
Standard input is empty
stdout
1
2
3
5
7