Advertisement
smatskevich

LNIP2

Mar 12th, 2022
1,153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.96 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4.  
  5. struct Node {
  6.   std::string Key;
  7.   Node* Next = nullptr;
  8.  
  9.   Node(const std::string& key) : Key(key) {}
  10. };
  11.  
  12. class HashTable {
  13.  public:
  14.   // Конструктор
  15.   HashTable(size_t initial_size) : table(initial_size, nullptr) {}
  16.  
  17.   bool Has(const std::string& key) const {
  18.     size_t h = (key.empty() ? 0 : key[0]) % table.size();
  19.     return HasInList(h, key);
  20.   }
  21.   bool Add(const std::string& key) {
  22.     size_t h = (key.empty() ? 0 : key[0]) % table.size();
  23.     if (HasInList(h, key)) return false;
  24.     Node* new_node = new Node(key);
  25.     new_node->Next = table[h];
  26.     table[h] = new_node;
  27.     return true;
  28.   }
  29.   bool Remove(const std::string& key) {
  30.     size_t h = (key.empty() ? 0 : key[0]) % table.size();
  31.     if (table[h] == nullptr) return false;
  32.     if (table[h]->Key == key) {
  33.       Node* next = table[h]->Next;
  34.       delete table[h];
  35.       table[h] = next;
  36.       return true;
  37.     }
  38.     for (Node* current = table[h]; current->Next != nullptr; current = current->Next) {
  39.       if (current->Next->Key == key) {
  40.         Node* next = current->Next->Next;
  41.         delete current->Next;
  42.         current->Next = next;
  43.         return true;
  44.       }
  45.     }
  46.     return false;
  47.   }
  48.  
  49.  private:
  50.   std::vector<Node*> table;
  51.  
  52.   bool HasInList(size_t h, const std::string& key) const {
  53.     for (Node* current = table[h]; current != nullptr; current = current->Next) {
  54.       if (current->Key == key) return true;
  55.     }
  56.     return false;
  57.   }
  58. };
  59.  
  60. int main() {
  61.   char command = 0;
  62.   std::string key;
  63.  
  64.   HashTable hash_table(80);
  65.   while (std::cin >> command >> key) {
  66.     if (command == '+')
  67.       std::cout << (hash_table.Add(key) ? "OK" : "FAIL") << std::endl;
  68.     else if (command == '-')
  69.       std::cout << (hash_table.Remove(key) ? "OK" : "FAIL") << std::endl;
  70.     else if (command == '?')
  71.       std::cout << (hash_table.Has(key) ? "OK" : "FAIL") << std::endl;
  72.   }
  73.  
  74.   return 0;
  75. }
  76.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement