首页 > 其他 > 详细

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

时间:2014-03-31 12:42:06      阅读:495      评论:0      收藏:0      [点我收藏+]

分离链接法(separate chaining):将散列到同一个值的所有元素保留到一个表中(用指针实现的单链表)。

bubuko.com,布布扣
/* 实现分离链接法所需要的类型声明 */

#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;
};
bubuko.com,布布扣
bubuko.com,布布扣
/* 分离链接散列表的初始化例程 */

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;
}
bubuko.com,布布扣
bubuko.com,布布扣
/* 分离链接散列表的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;
}
bubuko.com,布布扣
bubuko.com,布布扣
/* 分离链接散列表的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;
        }
    }
}
bubuko.com,布布扣

散列的冲突解决方法之分离链接法,布布扣,bubuko.com

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

原文:http://www.cnblogs.com/nufangrensheng/p/3635082.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!