关于书上的hash函数问题, 来自 数据结构与算法分析-C语言实现

Bureaucratist 2008-09-09 11:43:10


#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;
}



...全文
153 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
skyliuxu 2012-07-25
  • 打赏
  • 举报
回复
学习了,嘿嘿
test4ever 2008-09-10
  • 打赏
  • 举报
回复

Position pStart = (ListNode*)malloc( sizeof( struct ListNode ) * H->TableSize ); //一次性分配内存
for ( int j = 0; j < H->TableSize; j++)
{
H->TheLists[j] = pStart+j*sizeof(ListNode); //将各块地址分发给管理头
}


在8和9之间加入以上代码,然后将12去掉
Bureaucratist 2008-09-10
  • 打赏
  • 举报
回复
还得改一个地方,


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); //将各块地址分发给管理头
}

Bureaucratist 2008-09-10
  • 打赏
  • 举报
回复
原来如此! 谢谢!
Bureaucratist 2008-09-09
  • 打赏
  • 举报
回复
以上程序来自 书上 第5章散列表。
关于 散列表 的 分离链接法 规避散列冲突 的部分。

33,027

社区成员

发帖
与我相关
我的任务
社区描述
数据结构与算法相关内容讨论专区
社区管理员
  • 数据结构与算法社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧