《算法导论》——链接法解决哈希冲突

《算法导论》——链接法解决哈希冲突

教材是最好的老师!!
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
查找的最坏时间为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");
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值