#pragma once
#ifndef _HASHTABLE_H_
#define _HASHTABLE _H_
#include <assert.h>
#define DefaultSize 100
enum KindOfStatus {Active, Empty, Deleted};
struct Student
{
long ID_number;
char name[12];
char sex;
char address[12];
};
class HashTable
{
public:
HashTable(const int d, int sz=DefaultSize)
{
divitor=d;
TableSize=sz; CurrentSize=0;
ht=new Student[TableSize];
info=new KindOfStatus[TableSize];
for(int i=0; i<TableSize; ++i) info[i]=Empty;
}
~HashTable() {delete [] ht; delete [] info;}
bool Search(const long k1, Student& e1) const
{
int i=FindPos(k1);
if(info[i]!=Active||ht[i].ID_number!=k1) return false;
e1=ht[i];
return true;
}
bool Insert(const Student& e1)
{
long k1=e1.ID_number;
int i=FindPos(k1);
if(info[i]!=Active) //该桶为空;
{
ht[i]=e1; info[i]=Active;
CurrentSize++;
return true;
}
else if(info[i]==Active&&ht[i].ID_number==e1.ID_number) return false; //表中已有此元素;
else return false; //表已满;
}
bool Remove(const long k1, Student& e1)
{
int i=FindPos(k1);
if(info[i]==Active&&ht[i].ID_number==k1)
{
e1=ht[i];
info[i]=Deleted; CurrentSize--;
return true;
}
else return false;
}
void MakeEmpty() //清除散列表;
{
for(int i=0; i<TableSize; ++i) info[i]=Empty;
CurrentSize=0;
}
private:
int FindPos(const long k1) const //计算初始桶号;
{
int i=k1%divitor; int j=i;
do
{
if(info[j]==Empty||info[j]==Active&&ht[j].ID_number==k1) return j;
j=(j+1)%TableSize; //作循环处理,找下一个空桶;
} while(j!=i);
return j; //转圈回到开始点,表满,失败;
}
int operator==(Student& e1) {return *this==e1;}
int operator!=(Student& e1) {return *this!=e1;}
private:
int divitor;
int CurrentSize, TableSize;
Student *ht;
KindOfStatus *info;
};
#endif
哈希表---线性探测法
最新推荐文章于 2024-05-21 00:22:48 发布