码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-08-25 18:55:19      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:根据   typedef   signed   node   pos   +=   color   ++   定义   

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

 

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

标签:根据   typedef   signed   node   pos   +=   color   ++   定义   

原文地址:https://www.cnblogs.com/dzy521/p/9534803.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!