算法和数据结构项目练习5-哈希链表

Hash Chaining Table

项目介绍

  1. 本项目实现一个简单的哈希表。

  2. txt文件包含一个整数值序列。读取它们并使用链接构造一个哈希表。

  3. 程序应该依次读取每个整数,并使用mod 100作为哈希函数计算其哈希值。因此,如果键是k,那么哈希值h(k) =kmod 100。(最简单的哈希函数)

  4. 完成计算后打印:

    1. 哈希表中空条目的数量。
    2. 最长链的长度。
  5. 不使用STL或等价的库。

哈希表示例图如下:
在这里插入图片描述
读取的文件示例:
在这里插入图片描述

代码实现

#include <iostream>
#include <fstream>

using namespace std;

const int MAXNUM = 100;
int Lchaining = 0;
int tool = 0;
int key[MAXNUM];

struct Node {
	int value;
	Node* next;
	Node(int value) :value(value), next(0) {};
};

Node* Table[MAXNUM] = { 0 };

int hashfunction(int value);
void insert(int Key, int Value);
void chaincount(Node* node);

void insert(int Key, int Value) {
	Node* newNode = new Node(Value);
	int a = 1;
	if (Table[Key] == NULL) {
		Table[Key] = newNode;
	}
	else {
		Node* currentNode = Table[Key];
		while (currentNode->next != NULL) {
			a++;
			currentNode = currentNode->next;
		}
		if (a > Lchaining) {
			Lchaining = a;
		}
		currentNode->next = newNode;
	}
}

int main() {

	ifstream read;
	int key, value;
	string a;
	cout << "Please enter the filename: " << endl;
	cin >>a;
	read.open(a.c_str());
	if (!read)
	{
		cout << "Can't open file" << endl;
		exit(1);
	}
	while (read >> value) {
		key = hashfunction(value);
		insert(key, value);
	}
	int y = 0;
	while (y < 100) {
		y++;
		if (Table[y] == NULL) {
			tool++;
		}
	}
	cout << "The number of empty entries in the hash table: " << tool << endl;
	cout << "The length of the longest chain: " << Lchaining << endl;

	return 0;
}

int hashfunction(int value) {
	return value % 100;
}

输出结果如下图:

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值