11.1 直接寻址表
struct Node
{
int key;
int satellite;
};
Node *directAddressSearch(Node **T,int k)
{
return T[k];
}
void directAddressInsert(Node **T,Node *x)
{
T[x->key]=x;
}
void directAddressDelete(Node **T,Node *x)
{
T[x->key]=NULL;
delete x;
}
11.2 散列表
通过链接法解决冲突
(1)单链表
struct Node
{
int key;
int satellite;
Node *next;
};
void chainedHashInsert(Node **T,Node *x)
{
x->next=T[h(x->key)];
T[h(x->key)]=x;
}
Node *chainedHashSearch(Node **T,int k)
{
for(Node *p=T[h[k]];p;p=p->next)
{
if(p->key==k)return p;
}
return NULL;
}
void chainedHashDelete(Node **T,Node *x)
{
Node *y=x->next;
if(y) //x不是尾结点
{
x->key=y->key;
x->satellite=y->satellite;
x->next=y->next;
delete y;
}
else //x是尾结点
{
Node *p=T[h(x->key)];
if(p=x) //x是头节点
{
T[h(x->key)]=NULL;
delete p;
}
else //x不是头节点
{
Node *q=p->next;
while(q!=x)
{
p=q;q=q->next;
}
p->next=q->next;
delete q;
}
}
}
(2)双向链表
struct Node
{
int key;
int satellite;
Node *prev,*next;
};
void chainedHashInsert(Node **T,Node *x)
{
x->next=T[h(x->key)];
T[h(x->key)]=x;
if(x->next)x->next->prev=x;
}
Node *chainedHashSearch(Node **T,int k)
{
for(Node *p=T[h[k]];p;p=p->next)
{
if(p->key==k)return p;
}
return NULL;
}
void chainedHashDelete(Node **T,Node *x)
{
if(!x->prev&&!x->next) //x既是头节点,也是尾结点
{
T[h(x->key)]=NULL;
delete x;
}
else if(!x->prev) //x是头节点,不是尾结点
{
T[h(x->key)]=x->next;
x->next->prev=NULL;
delete x;
}
else if(!x->next) //x是尾结点,不是头节点
{
x->prev->next=NULL;
delete x;
}
else //x既不是头节点,也不是尾结点
{
x->prev->next=x->next;
x->next->prev=x->prev;
delete x;
}
}
11.3 散列函数
//除法散列法
int h(int k,int m)
{
return k%m;
}
//乘法散列法
int h(int k,int m,double A)
{
return int(m*(k*A-int(k*A)));
}
//全域散列法
//设计一个全域散列函数类,1<=a<=p-1,0<=b<=p-1
int h(int k,int m,int a,int b,int p)
{
return (a*k+b)%p%m;
}
11.4 开放寻址法
//没有删除操作
const int NIL=-1;
int hashInsert(int *T,int m,int k)
{
int i=0,j;
do
{
j=h(k,i);
if(T[j]==NIL)
{
T[j]=k;
return j;
}
else ++i;
}while(i!=m);
return NIL;
}
int hashSearch(int *T,int m,int k)
{
int i=0,j;
do
{
j=h(k,i);
if(T[j]==k)return j;
++i;
}while(T[j]!=NIL&&i!=m);
return NIL;
}
//有删除操作
const int NIL=-1,DELETED=-2;
int hashInsert(int *T,int m,int k)
{
int i=0,j;
do
{
j=h(k,i);
if(T[j]==NIL||T[j]==DELETED)
{
T[j]=k;
return j;
}
++i;
}while(i!=m);
return NIL;
}
int hashSearch(int *T,int m,int k)
{
int i=0,j;
do
{
j=h(k,i);
if(T[j]==k)return j;
++i;
}while(T[j]!=NIL&&i!=m);
return NIL;
}
int hashDelete(int *T,int m,int k)
{
int i=0,j;
do
{
j=h(k,i);
if(T[j]==k)
{
T[j]=DELETED;
return j;
}
++i;
}while(T[j]!=NIL&&i!=m);
return NIL;
}
//线性探查
h(k,i)=(h1(k)+i)%m
//二次探查
h(k,i)=(h1(k)+c1*i+c2*i*i)%m
//双重探查
h(k,i)=(h1(k)+i*h2(k))%m