33,027
社区成员




#ifndef _HashSep_H
#define _HashSep_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 are MakeEmpty are omitted */
#endif /* _HashSep_H */
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; //The Lists是一个指向指向ListNode结构的指针的指针。
};
散列表初始化例程
HashTable
InitializeTable( int TableSize )
{
HashTable H;
int i;
/* 1*/ if( TableSize < MinTableSize )
{
/* 2*/ Error( "Table size too small" );
/* 3*/ return NULL;
}
/* Allocate table */
/* 4*/ H = malloc( sizeof( struct HashTbl ) );
/* 5*/ if( H == NULL )
/* 6*/ FatalError( "Out of space!!!" );
/* 7*/ H->TableSize = NextPrime( TableSize ); //?
/* Allocate array of lists */
/* 8*/ H->TheLists = malloc( sizeof( List ) * H->TableSize );
/* 9*/ if( H->TheLists == NULL )
/*10*/ FatalError( "Out of space!!!" );
/* Allocate list headers */
/*11*/ for( i = 0; i < H->TableSize; i++ )
{
/*下面的部分,书上说,在循环中每次进行一词malloc,这样性能不高,
*一个好的替换方法是把 行12的部分去掉,而在for循环之前写上如下语句,
*H->TheLists[ i ] = malloc( sizeof( struct ListNode ) * H->TableSize );
*是否是要替换掉第8行?不知道应该怎么替换,希望各位前辈能指点一下,先谢过了
*/
/*12*/ H->TheLists[ i ] = malloc( sizeof( struct ListNode ) );
/*13*/ if( H->TheLists[ i ] == NULL )
/*14*/ FatalError( "Out of space!!!" );
else
/*15*/ H->TheLists[ i ]->Next = NULL;
}
/*16*/ return H;
}
Position pStart = (ListNode*)malloc( sizeof( struct ListNode ) * H->TableSize ); //一次性分配内存
for ( int j = 0; j < H->TableSize; j++)
{
H->TheLists[j] = pStart+j*sizeof(ListNode); //将各块地址分发给管理头
}
Position pStart = (ListNode*)malloc( sizeof( struct ListNode ) * H->TableSize ); //一次性分配内存
for ( int j = 0; j < H->TableSize; j++)
{
/*以下改为 H->TheLists[j] = pStart + j
*或者 H->TheLists[j] = &pStart[j]
*/
H->TheLists[j] = pStart+j*sizeof(ListNode); //将各块地址分发给管理头
}