#include<iostream>
using namespace std;
typedef int keyType;
typedef struct HashTable {
keyType key;
struct HashTable * next;
}HashTable, *HashTree;
class Hash {
public:
int curTable;//当前
//定义哈希函数
HashTree hashTable;
int maxTable;//表长
Hash(int length) {
curTable = 0;
maxTable = length;
hashTable = new HashTable[length];
for (int i = 0; i < length; i++)//初始化数值全为-1表示单元为空
{
hashTable[i].key = -1;
hashTable[i].next = NULL;
}
}
~Hash() {
delete[]hashTable;
hashTable = NULL;
}
int H(int key) {
return key % 7;
}
bool Insert(keyType & key) {
int ant = H(key);
HashTable * p = & hashTable[ant];
hashTable[ant].key = ant;
while ( p->next) {
if ( p-> next->key ==key) {
return false;
}
p = p->next;
}//while
HashTable *s = new HashTable;
s->key = key;
s->next = NULL;
p->next = s;
return true;
}
bool Delete(keyType & key) {
int ant = H(key);
HashTable * p = &hashTable[ant];
HashTable * s;
while (p->next) {
if (p->next->key == key) {
s = p->next;
p->next = s->next;
delete s;
s = NULL;
return true;
}
p = p->next;
}//while
return false;
}
void display()
{
for (int i = 0; i < maxTable; i++)
{
cout << i;
HashTable * s;
if (hashTable[i].key != -1) {
s = hashTable[i].next;
while (s != NULL) {
cout << "---->" << s->key;
s = s->next;
}
}
cout << endl;
}
}
//###重点:散列表的查找###//
int searchHash( keyType data) {
//如果成功,则放回单元标号,否则返回-1
int H0 = 0;
H0 = H(data);
if (hashTable[H0].key == -1) return -1;//没有存在
else if (hashTable[H0].key == H0) {
HashTable * s= hashTable[H0].next;
while (s != NULL) {
if (s->key == data) {
return H0;
}
s = s->next;
}
return -1;
}
}
};
int main() {
//针对课本课后习题
/*
对9,1,23,14,55,20,84,27,采用散列函数H(KEY)=KEY%7,表长度为10,链地址法的实现
*/
int a[] = { 9,1,23,14,55,20,84,27 };
int n = sizeof(a) / sizeof(a[0]);
cout << "n=" << n << endl;
Hash h(10);
for (int i = 0; i < n; i++)
h.Insert(a[i]);
h.display();
//delete
cout << "Please input the number you wanna delete" << endl;
keyType data;
while (cin>>data) {
if (data >= 0) {
if (h.Delete(data)) {
h.display();
}
else
cout << "不存在" << endl;
cout << "Please input the number you wanna delete" << endl;
}else
cout << "Please input the number you wanna delete" << endl;
}
//~delete
//locate
cout << "Please input the number you wanna locate" << endl;
while ( scanf_s("%d",&data)!=EOF ) {
if (data >= 0) {
if (h.searchHash( data) == -1) {
cout << "不存在" << endl;
}
else
cout << data<< " locates at hashTable[" << h.searchHash( data) <<"]"<< endl;
cout << "Please input the number you wanna locate" << endl;
}
else
cout << "Please input the number you wanna locate" << endl;
}
//~locate
return 0;
}