Hash Table 开放寻址处理冲突

来源:互联网 发布:2017seo内容编辑软件 编辑:程序博客网 时间:2024/05/16 07:00

Code:

#include <iostream>using namespace std;const int p = 7;const int N = 8;int T[N];/// 初始化void hash_init(){    for (int i = 0; i < N; ++i)    {        T[i] = -1;    }}/// 开放寻址int hash_fun(int value, int i)    {    return (value + i) % p;}void hash_insert(int value){   int key = hash_fun(value, 0);   for (int i = 1; i < p; ++i)   {       if (T[key] == -1)       {           T[key] = value;           break;       }        else        {            key = hash_fun(value, i);        }   }}int hash_search(int value){    int key = hash_fun(value, 0);    for (int i = 1; i < p; ++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 << endl << "No number!" << endl;   }}void hash_print(){    for (int i = 0; i < N; ++i)    {        cout << T[i] << "\t";    }}int main(){    int i;    int array[] = {5, 28, 19, 15, 20, 33};    for(i = 1; i <= N; ++i)    {        cout << i << "\t";    }    cout << endl;    hash_init();    hash_print();    cout << endl;    for (i = 0; i < sizeof(array)/sizeof(*array); ++i)    {        hash_insert(array[i]);    }    hash_print();    hash_delete(100);    hash_delete(5);    hash_print();    return 0;}


0 0
原创粉丝点击