#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");
}