#include \n#include \n\nconst int TABLE_SIZE = 100;\n\nstruct Node {\n int key;\n int value;\n Node* next;\n};\n\nclass HashTable {\nprivate:\n Node* table[TABLE_SIZE];\n\npublic:\n HashTable() {\n memset(table, 0, sizeof(table));\n }\n\n void insert(int key, int value) {\n int index = hashFunction(key);\n Node* newNode = new Node;\n newNode->key = key;\n newNode->value = value;\n newNode->next = nullptr;\n \n if (table[index] == nullptr) {\n table[index] = newNode;\n } else {\n Node* temp = table[index];\n while (temp->next != nullptr) {\n temp = temp->next;\n }\n temp->next = newNode;\n }\n }\n\n int search(int key) {\n int index = hashFunction(key);\n Node* temp = table[index];\n while (temp != nullptr) {\n if (temp->key == key) {\n return temp->value;\n }\n temp = temp->next;\n }\n return -1; // 表示未找到\n }\n\nprivate:\n int hashFunction(int key) {\n return key % TABLE_SIZE;\n }\n};\n\nvoid printBinary(const void* data, size_t size) {\n const unsigned char* bytes = static_cast<const unsigned char*>(data);\n for (size_t i = 0; i < size; ++i) {\n for (int j = 7; j >= 0; --j) {\n std::cout << ((bytes[i] >> j) & 1);\n }\n std::cout << " ";\n }\n std::cout << std::endl;\n}\n\nint main() {\n HashTable hashTable;\n\n // 插入元素\n hashTable.insert(1, 10);\n hashTable.insert(2, 20);\n hashTable.insert(3, 30);\n\n // 打印存储内容\n for (int i = 0; i < TABLE_SIZE; ++i) {\n Node* temp = hashTable.table[i];\n while (temp != nullptr) {\n printBinary(&temp->key, sizeof(temp->key));\n printBinary(&temp->value, sizeof(temp->value));\n temp = temp->next;\n }\n }\n\n return 0;\n}

C++ 自定义数据结构:哈希表实现及二进制存储显示

原文地址: https://www.cveoy.top/t/topic/pyrL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录