哈希函数示例

#include  " stdafx.h "
#include 
< malloc.h >
#include 
< stdio.h >
#include 
< iostream >
using   namespace  std;

typedef 
int  keytype;

typedef 
struct  chain
{
    keytype key;
    chain
*  next;
}chaintype;

int  HashInsert1(chaintype  * a[],keytype key, int  ( * Hash)(keytype, int ), int  mod);
chaintype
*  HashSearch1(chaintype *  a[],keytype key, int  ( * Hash)(keytype, int ), int  mod);
int  Hash1(keytype key, int  mod);

int  _tmain( int  argc, _TCHAR *  argv[])
{
    
int  i,key,mod = 10 ;
    
int  Test[ 10 ] = { 1 , 2 , 3 , 4 , 5 , 6 , 66 , 666 , 7 , 11 };
    chaintype
*  a[ 10 ], * p;
    
int * Hash)(keytype, int );
    
    
// 初始化哈希表
     for ( int  i = 0 ;i < 10 ;i ++ )
    {
       a[i]
= NULL;
    }
    
    Hash
= Hash1;
    
// 建立哈希表
     for ( int  i = 0 ;i < 10 ;i ++ )
    {
       HashInsert1(a,Test[i],Hash,mod);
    }
    
    
// 查找Key为666的记录
    key = 8 ;
    p
= HashSearch1(a,key,Hash,mod);
    
if (p != NULL) printf( " \n查找成功! " );
    
else  printf( " \n查找失败! " );
    
    
int  c;
    cin
>> c;
    
return   0 ;
}

// 哈希查找函数
chaintype *  HashSearch1(chaintype *  a[],keytype key, int  ( * Hash)(keytype, int ), int  mod)
{
    
int  i = Hash(key,mod);
    chaintype
*  cur = a[i];
    
    
while (cur != NULL  &&  cur -> key != key)
    {
        cur
= cur -> next;
    }
        
    
if (cur == NULL)  return  NULL;
    
else   return  cur;
}

// 用链式地址法解决哈希冲突
int  HashInsert1(chaintype  * a[],keytype key, int  ( * Hash)(keytype, int ), int  mod)
{
    
int  i = Hash(key,mod);
    chaintype 
* pre, * cur;   
    cur
= a[i];
    
    
while (cur != NULL  &&  cur -> key != key)
    {
        pre
= cur;
        cur
= cur -> next;        
    }
    
    
if (cur == NULL)
    {
        cur
= (chaintype * )malloc( sizeof (chaintype));
        cur
-> key = key;
        cur
-> next = NULL;          
        
        
if (a[i] == NULL) 
        {
            a[i]
= cur;
        }
        
else
        {
            pre
-> next = cur;
        }      
        
        
return   1 ;
    }
   
    
    
return   0 ;
}


// 除模取余的哈希函数
int  Hash1(keytype key, int  mod)
{
    
return  key % mod;
}

你可能感兴趣的:(函数)