Advertisement
Guest User

Untitled

a guest
Oct 21st, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.19 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. struct Node {
  6.   int data {0};
  7.   Node* next {nullptr};
  8. };
  9.  
  10.  
  11. class MySet {
  12. public:
  13.   Node* head {nullptr};
  14.   int size {0};
  15. public:
  16.   MySet() {  }
  17.  
  18.   void add(int value) {
  19.     ++size;
  20.  
  21.     if (head == nullptr) {
  22.       head = new Node;
  23.       head->data = value;
  24.       return;
  25.     }
  26.  
  27.     if (head->data == value)
  28.       throw invalid_argument("Already in set");
  29.  
  30.     Node* current = head;
  31.  
  32.     while (current->next != nullptr) {
  33.       current = current->next;
  34.       if (current->data == value)
  35.         throw invalid_argument("Already in set");
  36.     }
  37.  
  38.     current->next = new Node;
  39.     current->next->data = value;
  40.  
  41.   }
  42.  
  43.   int getSize() {
  44.     return size;
  45.   }
  46.  
  47.   bool count(int value) {
  48.     if (head == nullptr)
  49.       return false;
  50.  
  51.     Node* current = head;
  52.  
  53.     if (current->data == value)
  54.       return true;
  55.  
  56.     while(current->next != nullptr) {
  57.       current = current->next;
  58.       if (current->data == value)
  59.        return true;
  60.     }
  61.  
  62.     return false;
  63.   }
  64. };
  65.  
  66.  
  67. int main() noexcept {
  68.   MySet set;
  69.  
  70.   set.add(1);
  71.   set.add(1);
  72.  
  73.   for (int i = 0; i < 10; ++i)
  74.     set.add(i);
  75.  
  76.    cout << set.count(9);
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement