hash表:
1 hash三要素:
a,数据的范围:数据表示
b,合适的hash函数:如科学计数法
c,冲突的解决
1 源文件
#include<stdio.h>
#include<iostream>
using namespace std;
//保存数据的节点
struct Node
{
struct Node* pNext;
int data;
};
//一个数据:struct Node*
struct Hash_table
{
struct Node*** arr[10];
//vector<vector<vector<Node*>>> arr;
};
struct Node* createNode(int data);
struct Hash_table* createHash();
void initHash(struct Hash_table* hash);
void insertHash(struct Hash_table* hash, int data);
Node* findHash(struct Hash_table* hash, int data);
int main()
{
struct Hash_table* hash = createHash();
initHash(hash);
int a[10];
for (int i = 0; i < 10; i++)
{
a[i] = rand() % 100;
insertHash(hash, a[i]);
}
int n;
Node* p;
while (1)
{
scanf("%d", &n);
if (666 == n)break;
p = findHash(hash, n);
if (NULL == p)printf("wu\n");
else printf("is %d\n", p->data);
}
return 0;
}
//创建节点
struct Node* createNode(int data)
{
struct Node* pNew = new Node;
pNew->data = data;
pNew->pNext = NULL;
return pNew;
}
//创建哈希表
struct Hash_table* createHash()
{
struct Hash_table* pHash = new Hash_table;
return pHash;
}
//初始化哈希表
void initHash(struct Hash_table* hash)
{
memset(hash->arr, NULL, 4 * 10);
}
//插入数据到hash表中
void insertHash(Hash_table* hash, int data)
{
int ge, shi, bai;
ge = data % 10;
shi = data / 10 % 10;
bai = data / 100 % 10;
struct Node* temp;
if (hash->arr[ge] == NULL)
{
hash->arr[ge] = new Node * *[10];
memset(hash->arr[ge], 0, 4 * 10);
hash->arr[ge][shi] = new Node *[10];
memset(hash->arr[ge][shi], 0, 4 * 10);
hash->arr[ge][shi][bai] = createNode(data);
}
else
{
if (NULL == hash->arr[ge][shi])
{
hash->arr[ge][shi] = new Node * [10];
memset(hash->arr[ge][shi], 0, 4 * 10);
hash->arr[ge][shi][bai] = createNode(data);
}
else
{
if (NULL == hash->arr[ge][shi][bai])
{
hash->arr[ge][shi][bai] = createNode(data);
}
else
{
//冲突 插入到链表末尾
//定位末尾
temp = hash->arr[ge][shi][bai];
while (temp->pNext)
{
temp = temp->pNext;
}
//添加到末尾节点之后
temp->pNext = createNode(data);
}
}
}
}
//从hash表中找到数据并返回数据地址
Node* findHash(Hash_table* hash, int data)
{
int ge, shi, bai;
ge = data % 10;
shi = data / 10 % 10;
bai = data / 100 % 10;
struct Node* temp = NULL;
if (NULL == hash)return NULL;
if (NULL == hash->arr[ge])return NULL;
if (NULL == hash->arr[ge][shi])return NULL;
if (NULL == hash->arr[ge][shi][bai])return NULL;
temp = hash->arr[ge][shi][bai];
while (temp)
{
if (temp->data == data)
return temp;
temp = temp->pNext;
}
return NULL;
}