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;
    }
  • 相关阅读:
    Windows:Oracle 11g 备份脚本
    PLSQL操作Oracle创建用户和表
    Windows:添加、删除和修改静态路由
    Zabbix3.x 监控磁盘IO与自定义模板
    重置密码解决MySQL for Linux错误 ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
    Nginx日志格式log_format详解
    春的请柬
    Action Service Dao三层的功能划分
    关于正则表达式的排除
    jsp中对象的访问
  • 原文地址:https://www.cnblogs.com/dzy521/p/9534803.html
Copyright © 2011-2022 走看看