广工 数据结构 9.45

来源:互联网 发布:bug跟踪管理系统 java 编辑:程序博客网 时间:2024/04/30 19:20
9.45③  假设哈希表长为m,哈希函数为H(x),用链地址法
处理冲突。试编写输入一组关键字并建造哈希表的算法。


实现下列函数:
int BuildHashTab(ChainHashTab &H, int n, HKeyType es[]);
/* 直接调用下列函数                             */
/* 哈希函数:                                   */
/*    int Hash(ChainHashTab H, HKeyType k);     */
/* 冲突处理函数:                               */
/*    int Collision(ChainHashTab H, HLink &p);  */


哈希表的类型ChainHashTab定义如下:
#define NUM         7
#define NULLKEY    -1
#define SUCCESS     1
#define UNSUCCESS   0
#define DUPLICATE  -1


typedef char HKeyType;


typedef struct HNode {
   HKeyType  data;
   struct HNode*  next;
}*HLink;


typedef struct {
   HLink  *elem;  // 指针存储基址,动态分配数组
   int    count;  // 当前表中含有的记录个数
   int  cursize;  // 哈希表的当前容量
}ChainHashTab;    // 链地址哈希表


int Hash(ChainHashTab H, HKeyType k) {
  // 哈希函数
  return k % H.cursize;
}


Status Collision(ChainHashTab H, HLink &p) {
  // 求得下一个探查地址p 
  if (p && p->next) { 
    p = p->next;
    return SUCCESS;
  } else return UNSUCCESS;

}


int BuildHashTab(ChainHashTab &H, int n, HKeyType es[]) 
/* 直接调用下列函数                             */
/* 哈希函数:                                   */
/*    int Hash(ChainHashTab H, HKeyType k);     */
/* 冲突处理函数:                               */
/*    int Collision(ChainHashTab H, HLink &p);  */
{


       int i = 0, l, flag;
       HLink p, node;
         
       while( es[i] ){     
           l = Hash( H, es[i] );     
           node = ( HLink )malloc( sizeof( HNode ) );
           node->data = es[i];
           node->next = NULL;     
           i++;
     
           if( !H.elem[l] )     
               H.elem[l] = node;     
           else {     
               flag = 0;     
               p = H.elem[l];     
               if( p->data == node->data )     
                    flag = 1;
     
               while( Collision( H, p ) )     
                   if( p->data == node->data ) {     
                        flag = 1;
                        break;     
                    }     
               if( !flag ){
                    p = H.elem[l];     
                    node->next = p;     
                    H.elem[l] = node;     
               }     
           }     
        }
}

0 0