Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <unordered_set>
- #include <vector>
- int Hash(const std::string& key) {
- if (key.empty()) return 0;
- return key.front();
- }
- struct HTNode {
- std::string Key;
- HTNode* Next = nullptr;
- HTNode(std::string key) : Key(std::move(key)) {}
- };
- class HashTable {
- public:
- explicit HashTable(int initial_size = 80) : table(initial_size) {}
- ~HashTable();
- bool Has(const std::string& key) const;
- bool Add(const std::string& key);
- bool Remove(const std::string& key);
- private:
- std::vector<HTNode*> table;
- };
- HashTable::~HashTable() {
- }
- bool HashTable::Has(const std::string& key) const {
- int hash = Hash(key) % static_cast<int>(table.size());
- for (HTNode* node = table[hash]; node; node = node->Next)
- if (node->Key == key) return true;
- return false;
- }
- bool HashTable::Add(const std::string& key) {
- int hash = Hash(key) % static_cast<int>(table.size());
- if (!table[hash]) {
- table[hash] = new HTNode(key);
- return true;
- }
- for (HTNode* node = table[hash]; true; node = node->Next) {
- if (node->Key == key) return false;
- if (!node->Next) {
- node->Next = new HTNode(key);
- return true;
- }
- }
- }
- bool HashTable::Remove(const std::string& key) {
- int hash = Hash(key) % static_cast<int>(table.size());
- if (!table[hash]) return false;
- if (table[hash]->Key == key) {
- HTNode* to_delete = table[hash];
- table[hash] = to_delete->Next;
- delete to_delete;
- return true;
- }
- for (HTNode* node = table[hash]; node->Next; node = node->Next) {
- if (node->Next->Key == key) {
- HTNode* to_delete = node->Next;
- node->Next = to_delete->Next;
- delete to_delete;
- return true;
- }
- }
- return false;
- }
- int main1() {
- HashTable my_table;
- char command = 0;
- std::string key;
- while (std::cin >> command >> key) {
- switch (command) {
- case '?':
- std::cout << (my_table.Has(key) ? "OK" : "FAIL") << std::endl;
- break;
- case '+':
- std::cout << (my_table.Add(key) ? "OK" : "FAIL") << std::endl;
- break;
- case '-':
- std::cout << (my_table.Remove(key) ? "OK" : "FAIL") << std::endl;
- break;
- }
- }
- return 0;
- }
- class my_hash {
- public:
- size_t operator()(const std::string& str) const { return str.empty() ? 0 : str.front(); }
- };
- int main() {
- std::unordered_set<std::string, my_hash> table;
- char command = 0;
- std::string key;
- while (std::cin >> command >> key) {
- switch (command) {
- case '?':
- std::cout << (table.count(key) != 0 ? "OK" : "FAIL") << std::endl;
- break;
- case '+':
- std::cout << (table.insert(key).second ? "OK" : "FAIL") << std::endl;
- break;
- case '-':
- std::cout << (table.erase(key) ? "OK" : "FAIL") << std::endl;
- break;
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement