首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >链地址法处理hash冲突建立Hash表代码练习

链地址法处理hash冲突建立Hash表代码练习

作者头像
lexingsen
发布于 2022-02-25 08:23:10
发布于 2022-02-25 08:23:10
7650
举报
文章被收录于专栏:乐行僧的博客乐行僧的博客

给定一个数组x[] = {4, 1, 3, 7, 8, 22, 45, 75}, 哈希函数为H(key) = key*2 % 11,采用链地址法处理哈希冲突。建立哈希表:

代码语言:javascript
复制
#include <bits/stdc++.h>
using namespace std;
const int maxsize = 11;

//哈希函数
int hash(int x) {return x*2 % maxsize;}

struct node {
	int val;
	node *next;
	
	node() {}
	node(int x, node *next) {
		this->val = x;
		this->next = next;
	}
};

node hashtable[maxsize];

int x[] = {4, 1, 3, 7, 8, 22, 45, 75};
void chain() {
	for (int i=0; i<maxsize; ++i) hashtable[i].next  = NULL;
	int n = sizeof(x) / sizeof(int);
	for (int i=0; i<n; ++i) {
		int addr = hash(x[i]);
		auto p = new node(x[i], hashtable[addr].next);
		hashtable[addr].next = p;
	}
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档