【发布时间】:2013-11-18 05:35:17
【问题描述】:
我有一个包含歌曲列表的哈希表。通过将歌曲的标题翻译成它的 ascii 字符并使用这个数字 [% table size] 作为键,每个歌曲节点都被插入到表中。每个歌曲节点中还有一个“艺术家”字段。如果我想显示特定艺术家的每首歌曲,我可以在不搜索整个表中的每个节点的情况下这样做吗?我在下面包含了我的插入和散列方法。顺便说一句,散列函数的合适名称是什么?
头文件:
struct song {
string title;
string artist;
song* next;
};
class hash {
public:
hash();
int Hash_Key(string key); // For determining the hash key for a string
// Do I need to use multiple hash functions or multiple strings?
int Add_Item(string title, string artist); // for adding song to hash table
private:
static const int tableSize = 7;
song* HashTable[tableSize];
};
实施:
int hash::Add_Item(string title, string artist) {
int index = Hash_Key(name);
if(HashTable[index]->title == "empty") { // if first item at this index
HashTable[i]->title = title;
HashTable[i]->artist = artist;
}
else { // if not the first item at this index
song* temp = HashTable[index];
song* n = new song;
n->title = title;
n->artist = artist;
n->next = NULL;
while(temp->next != NULL) {
temp = temp->next;
}
temp->next = n;
}
return 0; // temporary
};
int hash::Hash_Key(string key) {
int hash = 0;
for(int i = 0; i < key.length(); i++) {
hash = hash + (int)key[i];
}
index = hash % tableSize; // remainder of the sum of ascii values of key
// divided by tableSize
return index;
}
【问题讨论】:
-
“不使用密钥搜索哈希表” - 你能做的最好的事情是 O(N)
-
这不是一个很好的哈希函数。见research.cs.vt.edu/AVresearch/hashing/strings.php