【问题标题】:Creating a hash table representation using an array in C++在 C++ 中使用数组创建哈希表表示
【发布时间】:2012-06-02 00:47:46
【问题描述】:

如何使用 C++ 中的数组为表创建哈希表表示,并对其应用诸如 k % 10 之类的哈希函数?我将使用链接来解决冲突(即表是一个链表数组)。

我还要在此表中插入、搜索和删除值。

到目前为止,我有:

struct Node {
    int value;
    Node* next;
}; 

void insert(int n, Node* hashtable[]) {

    int x = n % 10;
... ...

例如对于值10,我的哈希函数将产生0,所以10 进入数组/哈希表的第一个槽。
如果我有 100 的值,100 也将转到第一个插槽,所以我的 10 将“指向”100...我将如何编码?

【问题讨论】:

  • 如果你接触过哈希,你肯定学过链表吗?因为链表比散列更基础。

标签: c++ arrays hash chaining


【解决方案1】:

类似

Node* oldFront = hashtable[hashcode];
Node* newNode = new Node(value, oldFront);
hashtable[hashcode] = newNode;

这会将最近的碰撞添加到链表的前面,即它作为堆栈运行。将其添加到后面作为提问者的练习!

【讨论】:

  • 假设我想在我的链表数组中的某个位置放置一些东西(例如,我想在 myarray[2] 中放置“2”。myarray[2] 可能已经有一个值(s )那里。我该怎么做?)
  • 你将它添加到 myarray[2] 中的链表中。
猜你喜欢
  • 1970-01-01
  • 2011-03-07
  • 2010-12-04
  • 2015-09-24
  • 1970-01-01
  • 2012-02-09
  • 2018-01-26
  • 2021-02-15
  • 2022-11-23
相关资源
最近更新 更多