fork download
  1. #include <iostream>
  2.  
  3. // since you wanna have all of Node in public, declare as struct
  4. struct Node
  5. {
  6. char data;
  7. int count = 1;
  8. Node* next_node = nullptr;
  9. Node(const char& a) // create a constrcor which will initilize data
  10. : data(a) {} // at the time of Node creation
  11. };
  12.  
  13. class set
  14. {
  15. private:
  16. Node *head; // need only head, if it's a simple list
  17. public:
  18. set() :head(nullptr) {} // constructor set it to nullptr
  19. ~set()
  20. {
  21. Node* temp = head;
  22. while( temp != nullptr )
  23. {
  24. Node* next = temp->next_node;
  25. //std::cout << "deleting \t" << temp->data << std::endl;
  26. delete temp;
  27. temp = next;
  28. }
  29. head = nullptr;
  30. }
  31.  
  32. inline bool isAvailable(const char& value)
  33. {
  34. Node *findPos = head;
  35.  
  36. while(findPos != nullptr)
  37. {
  38. if(findPos -> data == value) return true;
  39. else findPos = findPos->next_node;
  40. }
  41. return false;
  42. }
  43.  
  44. void insert(const char& value)
  45. {
  46. if(head == nullptr) // first case
  47. {
  48. Node *newNode = new Node(value);
  49. newNode->next_node = head;
  50. head = newNode;
  51. }
  52. else if(isAvailable(value)) // if node available
  53. {
  54. Node *temp = head;
  55. while(temp->data != value) // find the node
  56. temp = temp->next_node;
  57. temp->count += 1; // and count it by 1
  58. }
  59. else // all new nodes
  60. {
  61. Node *temp = head;
  62. while(temp->next_node != nullptr) // to find the null point (end of list)
  63. temp = temp->next_node;
  64.  
  65. temp = temp->next_node = new Node(value);
  66. }
  67. }
  68.  
  69. void print() const // just to print
  70. {
  71. Node *temp = head;
  72. while(temp != nullptr)
  73. {
  74. std::cout << temp->data << " " << temp->count << "\n";
  75. temp = temp->next_node;
  76. }
  77. }
  78. };
  79.  
  80.  
  81. int main()
  82. {
  83. ::set mySet;
  84.  
  85. mySet.insert('a');
  86. mySet.insert('a');
  87. mySet.insert('b');
  88. mySet.insert('b');
  89. mySet.insert('c');
  90. mySet.insert('a');
  91.  
  92. mySet.print();
  93.  
  94. return 0;
  95. }
  96.  
Success #stdin #stdout 0s 4456KB
stdin
Standard input is empty
stdout
a 3
b 2
c 1