zoukankan      html  css  js  c++  java
  • 哈希表之开散列表——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] = '';
        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 != '')
            HashVal += *Key++;
    
        return HashVal%TableSize;
    }
    
    //根据Horner准则
    //涉及到关键字的所有字符 分布的好
    Index Hash(const char* Key, int TableSize)
    {
        unsigned int    HashVal = 0;
    
        while(*Key != '')
            HashVal = (HashVal<<5) + *Key++;
    
        return HashVal%TableSize;
    }
  • 相关阅读:
    js的内置对象arguments
    typeof
    JS 数组赋值,引用传递 问题
    技术突围打造创新解决方案 思岚科技让机器人移动更智能
    2020思岚科技第四季度大事记
    校企合作 | 上海交通大学 X 思岚科技“智能感知创新实验室”正式揭牌
    新基建下的智慧货架机器人,已迎来“下半场”应用期
    2020思岚科技第二季度大事记
    思岚科技2020第一季度大事记
    思岚科技2019第四季度大事件
  • 原文地址:https://www.cnblogs.com/dzy521/p/9534803.html
Copyright © 2011-2022 走看看