fork download
  1. #include <iostream>
  2. #include <set>
  3.  
  4. using namespace std;
  5.  
  6. struct Node{
  7. int data;
  8. Node* next;
  9. };
  10.  
  11. set<int> hashmap;
  12. Node* head = NULL;
  13.  
  14. void deldups()
  15. {
  16. Node* prev = NULL;
  17. Node* curr = head;
  18.  
  19. while (curr != NULL)
  20. {
  21. int val = curr->data;
  22. if (!hashmap.insert(val).second)
  23. {
  24. prev->next = curr->next;
  25. delete curr;
  26. }
  27. else
  28. {
  29. prev = curr;
  30. }
  31. curr = prev->next;
  32. }
  33. }
  34.  
  35. void print()
  36. {
  37. Node* temp = head;
  38. while (temp != NULL)
  39. {
  40. cout << temp->data << " ";
  41. temp = temp->next;
  42. }
  43. cout << endl;
  44. }
  45.  
  46. int main()
  47. {
  48. Node* firstnode = new Node();
  49. head = firstnode;
  50. firstnode->data = 5;
  51.  
  52. Node* secondnode = new Node();
  53. firstnode->next = secondnode;
  54. secondnode->data = 6;
  55.  
  56. Node* thirdnode = new Node();
  57. secondnode->next = thirdnode;
  58. thirdnode->data = 7;
  59.  
  60. Node* forthnode = new Node();
  61. thirdnode->next = forthnode;
  62. forthnode->data = 5;
  63.  
  64. Node* fifthnode = new Node();
  65. forthnode->next = fifthnode;
  66. fifthnode->data = 9;
  67. fifthnode->next = NULL;
  68.  
  69. cout << "before: "; print();
  70. deldups();
  71. cout << "after: "; print();
  72.  
  73. return 0;
  74. }
Success #stdin #stdout 0.01s 5456KB
stdin
Standard input is empty
stdout
before: 5 6 7 5 9 
after: 5 6 7 9