除留余数法和链地址法构造散列表
实现
#pragma once
#include <iostream>
using namespace std;
#define LEN 13
typedef struct hash_node
{
int data;
struct hash_node* next;
}hash_node;
typedef hash_node* HashTable[LEN];
void InitHashTable(HashTable& ht)
{
for (int i = 0; i < LEN; i++)
{
ht[i] = NULL;
}
}
int Hash(int key)
{
return key % LEN;
}
void InsertHashTable(HashTable& ht,int key)
{
int index = Hash(key);
hash_node* s = new hash_node;
s->data = key;
if (ht[index] == NULL)
{
s->next = ht[index];
ht[index] = s;
}
else
{
hash_node* temp = ht[index];
while (temp->next != NULL)
{
temp = temp->next;
}
s->next = temp->next;
temp->next = s;
}
}
void ShowHashTable(HashTable& ht)
{
for (int i = 0; i < LEN; i++)
{
cout << i <<": ";
hash_node* p = ht[i];
while (p != NULL)
{
printf("%d-->", p->data);
p = p->next;
}
cout << endl;
}
}
int main()
{
HashTable ht;
InitHashTable(ht);
int array[] = { 19,14,23,1,68,20,84,27,55,11,10,79 };
for (int i = 0; i < sizeof(array) / sizeof(int); i++)
{
InsertHashTable(ht, array[i]);
}
cout << "散列表为:" << endl;
ShowHashTable(ht);
system("pause");
return 0;
}
运行结果