大话数据结构学习笔记(12)C++实现哈希表(分离链接法,插入,删除,遍历)

本文介绍了一种基于C++实现的哈希表结构,包括插入、删除等基本操作,并展示了如何通过简单的程序实例来验证这些操作的有效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
#include<vector>
#include<deque>
using namespace std;

class HashTable
{
public:
	HashTable(int n);
	~HashTable() = default;
	bool insertRecord(const int m);  //插入一个值
	void removeRecord(const int m);//删除一个值
	void printHash()const;			//打印哈希表
private:
	vector<deque<int>> HashItem;
	int HashTablesize = 0;
};

HashTable::HashTable(int n)
{
	HashTablesize = n;

	for (int i = 0; i < n; i++)
	{
		deque<int> adeque;
		HashItem.push_back(adeque);
	}
}

bool HashTable::insertRecord(const int m)
{
	int position = m%HashTablesize;
	if (position >= HashTablesize || position < 0)
	{
		return false;
	}
	else
	{
		HashItem.at(position).push_front(m);//插入到队头
		return true;
	}
}

void HashTable::removeRecord(const int m)
{
	for (int i = 0; i < HashTablesize; i++)
	{
		for (int j = 0; j < static_cast<int>(HashItem.at(i).size()); j++)
		{
			if (HashItem.at(i).at(j) == m)
			{
				HashItem.at(i).erase(HashItem.at(i).begin() + j);//删除记录
			}
		}
	}
}

void HashTable::printHash()const
{
	for (int i = 0; i < HashTablesize; i++)
	{
		for (int j = 0; j < HashItem.at(i).size(); j++)
		{
			cout << HashItem.at(i).at(j) << " ";
		}
		cout << endl;
	}
}
void main()
{
	HashTable h(10);
	for (int i = 0; i < 100; i++)
	{
		h.insertRecord(i);
	}
	h.printHash();
	h.removeRecord(66);
	h.removeRecord(80);
	h.printHash();
	system("pause");
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值