如何在内存中生成一个哈希表,长度为m?

如题所述

23,除留取余法,若哈希表长为M,则取余因子P为小于,或等于表长(最好接近M)的最小质数或不包含小于20质因子的合数。

取关键字或关键字的某个线性函数值为散列地址。即H(key)=key或H(key) = a·key + b,其中a和b为常数(这种散列函数叫做自身函数)。若其中H(key)中已经有值了,就往下一个找,直到H(key)中没有值了,就放进去。

扩展资料:

#include <iostream>

using namespace std

//哈希函数的构造方法:除留取余法

//处理冲突机制:链地址法

typedef struct _NODE

{

int key;

struct _NODE* next;

}_NODE;

typedef struct Hash_Table

{

_NODE* pChainHash[13];

}Hash_Table;

//初始化哈希表

Hash_Table* InitHashTable()

{

Hash_Table* pHashTable = new Hash_Table;

memset( pHashTable, 0, sizeof(Hash_Table) );

return pHashTable;

}

//在哈希表中查找数据

_NODE* FindDataInHash( Hash_Table* pHashTable, int key )

{

if ( !pHashTable )

return NULL;

_NODE* pNode = NULL;

if ( !(pNode = pHashTable->pChainHash[ key % 13 ] ) )

return NULL;

while ( pNode )

{

if ( pNode->key == key )

return pNode;

pNode = pNode->next;

}

return NULL;

}

//在哈希表中插入数据

bool InsertDataToHash( Hash_Table* pHashTable, int key )

{

if ( !pHashTable )

return false;

if ( NULL != FindDataInHash( pHashTable, key ) )

return false;//数据已在里面

_NODE* pNewNode = new _NODE;

memset( pNewNode, 0, sizeof( _NODE ) );

pNewNode->key = key;

_NODE* pNode = NULL;

pNode = pHashTable->pChainHash[ key % 13 ];

if ( !pNode ) 

{

pHashTable->pChainHash[ key % 13 ] = pNewNode;

}

else

{

while( pNode->next )

{

pNode = pNode->next;

 }

pNode->next = pNewNode;

}

return true;

}


温馨提示:答案为网友推荐,仅供参考