📜  用于链式哈希的C ++程序(1)

📅  最后修改于: 2023-12-03 15:27:12.390000             🧑  作者: Mango

用于链式哈希的C++程序

链式哈希是一种键值对存储的数据结构,它使用哈希函数将键映射到桶中,并使用链表来解决哈希冲突。链式哈希可以在插入和查找操作中实现常数时间的平均复杂度,并且很容易动态调整桶的数量。

实现步骤
  1. 定义链表节点结构体,存储键值对和指向下一个节点的指针。
  2. 定义哈希表类,包含哈希表大小、桶数组、哈希函数、插入和查找操作函数等。
  3. 构造函数中初始化桶数组,将每个桶的头节点指向 NULL。
  4. 定义哈希函数,将键的字符串表示转换成哈希值。
  5. 插入操作根据哈希值计算桶的索引,将键值对插入到对应的链表中。
  6. 查找操作同样根据哈希值计算桶的索引,遍历对应链表查找键是否存在。
struct ListNode {
    string key;
    int val;
    ListNode* next;
    ListNode(string k, int v) : key(k), val(v), next(NULL) {}
};

class HashTable {
  private:
    int size;
    vector<ListNode*> table;
    // 哈希函数
    int hashFunc(string key) {
        int hashValue = 0;
        for (char c : key) {
            hashValue = hashValue * 31 + int(c);
        }
        return hashValue % size;
    }
  public:
    // 构造函数
    HashTable(int s) : size(s), table(size, NULL) {}
    // 插入操作
    void put(string key, int val) {
        int index = hashFunc(key);
        ListNode* node = table[index];
        while (node) {
            if (node->key == key) {
                node->val = val;
                return;
            }
            node = node->next;
        }
        ListNode* newNode = new ListNode(key, val);
        newNode->next = table[index];
        table[index] = newNode;
    }
    // 查找操作
    int get(string key) {
        int index = hashFunc(key);
        ListNode* node = table[index];
        while (node) {
            if (node->key == key) {
                return node->val;
            }
            node = node->next;
        }
        return -1;
    }
};
使用示例
int main() {
    HashTable ht(100);  // 初始化哈希表,大小为100
    ht.put("apple", 10);  // 插入键值对
    ht.put("banana", 20);
    cout << "apple: " << ht.get("apple") << endl;  // 查找键的值
    cout << "banana: " << ht.get("banana") << endl;
    cout << "orange: " << ht.get("orange") << endl;
    return 0;
}

输出结果:

apple: 10
banana: 20
orange: -1
总结

链式哈希是一种常用的数据结构,用于实现插入和查找操作时间复杂度为常数的键值对存储。我们可以通过C++的类和结构体来实现链表和哈希表,只要掌握了哈希函数的设计方法,就能轻松编写出高效的链式哈希表程序。