说明:0-7相对于数组下标,每个数组元素下标又相当于一个单链表。
代码实现:
散列函数采用除留余数法,冲突解决采用链地址法。
#ifndef _HASH_H
#define _HASH_H
#define HASHSIZE 10
typedef struct Node {
int data;
Node *next;
}Node;
class HashTable {
private:
Node* node[HASHSIZE];
public:
HashTable();
int hash(int key);
Node* lookup(int key);
bool insert(int value);
void display();
};
#endif // !_HASH_H
#include "pch.h"
#include "hash.h"
#include<stdio.h>
#include<stdlib.h>
/*哈希表初始化*/
HashTable::HashTable()
{
for (int i = 0; i < HASHSIZE; i++)
{
node[i] = NULL;
}
}
/*哈希函数*/
int HashTable::hash(int key)
{
return key % HASHSIZE;
}
/*寻找元素*/
Node* HashTable::lookup(int value)
{
Node *np = NULL;
int index = 0;
/*根据哈希函数决定到数组下标为几(0-9)的单链表中寻找数据*/
index = hash(value);
/*循环判断数组下标为index的单链表中是否存在值为value的节点*/
for (np = node[index]; np; np = np->next)
{
if (value == np->data)
{
return np;
}
}
return NULL;
}
/*插入元素*/
bool HashTable::insert(int value)
{
int index = 0;
Node *np = NULL;
/*判断表中是否已经存在值为value这个元素*/
if (!(np = lookup(value)))
{
/*根据哈希函数决定插入位置*/
index = hash(value);
/*申请空间*/
np = (Node*)malloc(sizeof(Node));
if (!np)
return false;
np->data = value;
/*单链表的头插法操作*/
np->next = node[index];
node[index] = np;
}
/*表中有这个元素那就更改就好了*/
np->data = value;
return true;
}
/*遍历*/
void HashTable::display()
{
int index = 0;
int count = 0;
Node *np = NULL;
for (index = 0; index <HASHSIZE; index++)
{
count = 0;
for (np = node[index]; np!=NULL; np=np->next)
{
++count;
printf("第%d个链表的第%d个节点的数据元素为%d\n", index,count,np->data);
}
}
}
#include "pch.h"
#include <iostream>
#include "hash.h"
int main()
{
int value[8] = { 4,7,9,6,5,14,17,28 };
HashTable hash;
for (int i = 0; i < 8; i++)
{
hash.insert(value[i]);
}
hash.display();
return 0;
}