Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <vector>
- struct Node {
- std::string Key;
- Node* Next = nullptr;
- Node(const std::string& key) : Key(key) {}
- };
- class HashTable {
- public:
- // Конструктор
- HashTable(size_t initial_size) : table(initial_size, nullptr) {}
- bool Has(const std::string& key) const {
- size_t h = (key.empty() ? 0 : key[0]) % table.size();
- return HasInList(h, key);
- }
- bool Add(const std::string& key) {
- size_t h = (key.empty() ? 0 : key[0]) % table.size();
- if (HasInList(h, key)) return false;
- Node* new_node = new Node(key);
- new_node->Next = table[h];
- table[h] = new_node;
- return true;
- }
- bool Remove(const std::string& key) {
- size_t h = (key.empty() ? 0 : key[0]) % table.size();
- if (table[h] == nullptr) return false;
- if (table[h]->Key == key) {
- Node* next = table[h]->Next;
- delete table[h];
- table[h] = next;
- return true;
- }
- for (Node* current = table[h]; current->Next != nullptr; current = current->Next) {
- if (current->Next->Key == key) {
- Node* next = current->Next->Next;
- delete current->Next;
- current->Next = next;
- return true;
- }
- }
- return false;
- }
- private:
- std::vector<Node*> table;
- bool HasInList(size_t h, const std::string& key) const {
- for (Node* current = table[h]; current != nullptr; current = current->Next) {
- if (current->Key == key) return true;
- }
- return false;
- }
- };
- int main() {
- char command = 0;
- std::string key;
- HashTable hash_table(80);
- while (std::cin >> command >> key) {
- if (command == '+')
- std::cout << (hash_table.Add(key) ? "OK" : "FAIL") << std::endl;
- else if (command == '-')
- std::cout << (hash_table.Remove(key) ? "OK" : "FAIL") << std::endl;
- else if (command == '?')
- std::cout << (hash_table.Has(key) ? "OK" : "FAIL") << std::endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement