《算法导论》——链接法解决哈希冲突
教材是最好的老师!!
查找的最坏时间为O(n),删除的最坏时间为O(1).
#include "iostream"
#define MAX 6
using namespace std;
struct node //节点结构体
{
int value;
struct node* next;
struct node* pre;
};
node** Init()
{
node **tmp = new node* [MAX];//开辟存储Max个节点地址的空间(MAX个槽)
for (int i = 0; i < MAX; i++)//初始化空间
{
tmp[i] = NULL;
}
return tmp;
}
int Hashfunc(int n)//除法散列法,MAX不应为2的幂数,且最好接近于总数(时间最少)
{
return n % MAX;
}
void Insert(node** tmp, int* a, int j)
{
int ret = 0;
if (tmp == NULL || a == NULL || j < 0)
{
ret = -1;
cout << "func Insert err: %d" << ret << endl;
exit(0);
}
node* n = new node [sizeof(node)];
n->next = NULL;
n->pre = NULL;
n->value = a[j];
int key = Hashfunc(a[j]);
n->next = tmp[key]; //头插
if (tmp[key] != NULL)
{
tmp[key]->pre = n;
}
tmp[key] = n; //新节点n放在头部
}
node* Search_value(node** tmp, int a)
{
int ret = 0;
if (tmp == NULL )
{
ret = -2;
cout << "func Search_value() err: %d" << ret << endl;
return NULL;
}
node * se = NULL;
int key = Hashfunc(a);
node* t = tmp[key];
while (t!=NULL && t->value != a)
{
t = t->next;
}
if (t == NULL)
{
cout << "未搜索到数据" << a << endl;
return NULL;
}
else if (t->value == a)
{
cout << "数据" << a << "在记录中" << endl;
return t;
}
}
void Dele_value(node** tmp, int a)
{
int ret = 0;
if (tmp == NULL)
{
ret = -3;
cout << "func Dele_value() err: %d" << ret << endl;
exit(0);
}
node* m = Search_value(tmp, a);
if (m != NULL)
{
if (m->next == NULL && m->pre!=NULL) //数据在尾部
{
m->pre->next = m->next;
}
else if (m->pre == NULL ) //数据在头部
{
tmp[Hashfunc(m->value)] = m->next;
delete m;
}
else
{
m->pre = m->next->pre;
m->pre->next = m->next;
}
cout << "删除成功" << endl;
}
}
void Display(node** tmp)
{
node *current = NULL;
for (int i = 0; i < MAX; i++)
{
current = tmp[i];
if (current == NULL)
{
cout << "第" << i << "个槽为NULL" << endl;
continue;
}
else
{
cout << "第" << i << "个槽为";
while (current != NULL)
{
cout << current->value << " ";
current = current->next;
}
cout << endl;
}
}
}
void main()
{
int a[] = { 3,9,8,7,10,45,19 };
int len = sizeof(a) / sizeof(a[0]);
node** tmp = Init();
for (int i = 0; i < len; i++)
{
Insert(tmp, a, i);
}
Display(tmp);
Search_value(tmp, 20);
Dele_value(tmp, 19);
Display(tmp);
system("pause");
}