不怎么明白原理,参照一个网友的代码,自己写了一下,算是练手吧:
#include <iostream>
using namespace std;
const int m = 19;
int T[30];
void hasn_init()
{
for (int i = 0; i < 30; ++i)
{
T[i] = -1;
}
}
int hash_fun(int value)
{
return value;
}
int hash_fun(int value, int i)
{
return (hash_fun(value) + i) % m;
}
int hash_insert(int value)
{
int key = hash_fun(value,0);
for (int i = 0; i < m; ++i)
{
if (T[key] == -1)
{
T[key] = value;
return key;
}
key = hash_fun(value,i);
}
return -1;
}
int hash_search(int value)
{
int key = hash_fun(value,0);
for (int i = 1; i < m; ++i)
{
if (T[key] == value )
{
return key;
}
if (T[key] == -1)
{
return -1;
}
key = hash_fun(value,i);
}
return -1;
}
void hash_delete(int value)
{
int result = hash_search(value);
if (result != -1)
{
T[result] = -1;
}
else
{
cout << "error" << endl;
}
}
void hash_print()
{
for (int i = 0; i < 30;++i)
{
if (T[i] != -1)
{
cout << i << " : " << T[i] << endl;
}
}
}
int main()
{
int a[]={5,28,19,15,20,33,12,17,10};
hasn_init();
for (int i = 0; i < sizeof(a)/sizeof(*a); ++i)
{
hash_insert(a[i]);
}
hash_print();
hash_delete(100);
hash_delete(5);
hash_print();
}