哈希表之开散列表——key为字符串.c

#define KEYLENGTH 15
typedef char ElementType[KEYLENGTH+1];
typedef int Index;

/*定义单链表*/
typedef struct LNode *PtrToNode;
struct LNode{
   ElementType Data;
   PtrToNode Next;
};
typedef PtrToNode Position;
typedef PtrToNode List;

typedef struct  TblNode *HashTable;
struct TblNode{
   int TableSize;
   List Heads;
};


HashTable CreateTable(int TableSize)
{
  HashTable H;
  int i;

  H = (HashTable)malloc(sizeof(struct TblNode));
  H->TableSize = NextPrime(TableSize);

  H->Heads = (List)malloc(sizeof(struct LNode)*H->TableSize);
  for(i=0;i<H->TableSize;i++)
  {
    H->Heads[i].Data[0] = '\0';
    H->Heads[i].Next = NULL;
  }
  return H;
}


Position Find(HashTable H, ElementType Key)
{
   Position P;
   Index Pos;

   Pos = Hash(Key, H->TableSize);  //调用散列函数 得到位置
   P = H->Heads[Pos].Next;

   while( P && strcmp(P->Data, Key))
   {
     P = P->Next;
   }

   return P;
}

bool Insert(HashTable H, ElementType Key)
{
  Position P,NewCell;
  Index Pos;

  P = Find(H,Key);
  if(!P)
  {
    NewCell = (Position)malloc(sizeof(struct LNode));
    strcpy(NewCell.Data,Key);
    Pos = Hash(Key, H->TableSize);
    NewCell->Next = H->Heads[Pos].Next;
    H->Heads[Pos].Next = NewCell;
    return true;
  }
  else
  {
    return false;
  }
}

void DestroyTable(HashTable H)
{
   int i;
   Position P,Tmp;

   for(i=0;i<H->TableSize;i++)
   {
      P = H->Head[i].Next;
      while(P)
      {
         Tmp = P->Next;
         free(P);
         P = Tmp;
      }
   }
   free(H->Heads);
   free(H);
}

 

Hash函数构造:

//一个简单的散列函数
typedef unsigned int Index;
Index Hash(const char* Key, int TableSize)
{
    unsigned int    HashVal = 0;

    while(*Key != '\0')
        HashVal += *Key++;

    return HashVal%TableSize;
}

//根据Horner准则
//涉及到关键字的所有字符 分布的好
Index Hash(const char* Key, int TableSize)
{
    unsigned int    HashVal = 0;

    while(*Key != '\0')
        HashVal = (HashVal<<5) + *Key++;

    return HashVal%TableSize;
}

 

posted @ 2018-08-25 17:38  花花与小叮当  阅读(781)  评论(0编辑  收藏  举报