您的位置:首页 > 其它

散列的冲突解决方法之分离链接法

2014-03-31 09:33 369 查看
分离链接法(separate chaining):将散列到同一个值的所有元素保留到一个表中(用指针实现的单链表)。

/* 实现分离链接法所需要的类型声明 */

#ifndef _HashSep_H
#define _HahsSep_H

struct ListNode;
typedef struct ListNode *Position;
struct HashTbl;
typedef struct HashTbl *HashTable;

HashTable InitializeTable( int TableSize );
void DestroyTable( HashTable H );
Position Find( ElementType Key, HashTable H );
void Insert( ElementType Key, HashTable H );
ElementType Retrieve( Position P );
/* Routines such as Delete and MakeEmpty are omitted */

#endif     /* _HashSep_H */

/* Place in the implementation file */
struct ListNode
{
ElementType Element;
Position    Next;
};

typedef Position List;

/* List *TheList will be an array of lists, allocated later */
/* The lists use headers(for simplicity */
/* though this wastes space */
struct HashTbl
{
int TableSize;
List *TheLists;
};


/* 分离链接散列表的初始化例程 */

HashTable
InitializeTable( int TableSize )
{
HashTable H;
int i;

if( TableSize < MinTableSize )
{
Error( "Table size too small" );
return NULL;
}

/* Allocate table */
H = malloc( sizeof( struct HashTbl ));
if( H == NULL )
FatalError( "Out of space!!!" );

H->TableSize = NextPirme( TableSize );

/* Allocate array of lists */
H->TheLists = malloc( sizeof( List ) * H->TableSize );
if( H->Thelists == NULL )
FatalError( "Out of space!!!" );

/* Allocate list headers */
for( i = 0; i < H->TableSize; i++)
{
H->TheLists[ i ] = malloc( sizeof( struct ListNode ) );
if( H->TheLists[ i ] == NULL)
FatalError( "Out of space!!!" );
else
H->TheLists[ i ]->Next = NULL;
}

return H;
}


/* 分离链接散列表的Find例程 */

Position
Find( ElementType Key, HashTable H )
{
Position P;
List L;

L = H->TheLists[ Hash( Key, H->TableSize ) ];
P = L->Next;
while( P != NULL && P->Element != Key )        /* Probably need strcmp!! */
P = P->Next;

return P;
}


/* 分离链接散列表的Insert例程 */

void
Insert( ElementType Key, HashTable H )
{
Position Pos, NewCell;
List L;

Pos = Find( Key, H );
if( Pos == NULL )    /* Key is not found */
{
NewCell = malloc( sizeof( struct ListNode ) );
if( NewCell == NULL )
FatalError( "Out of space!!!" );
else
{
L = H->TheLists[ Hash( Key, H->TableSize ) ];
NewCell->Next = L->Next;
NewCell->Element = Key;    /* Probably need strcpy ! */
L->Next = NewCell;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: