zoukankan      html  css  js  c++  java
  • 开放地址法散列表ADT

    数据结构定义如下:

     1 typedef unsigned int Index;
     2 typedef Index Position;
     3 
     4 struct HashTbl;
     5 typedef struct HashTbl *HashTable;
     6 
     7 HashTable InitializeTable(int TableSize);
     8 void DestroyTable(HashTable H);
     9 Position Find(ElementType Key, HashTable H);
    10 void Insert(ElementType Key, HashTable H);
    11 ElementType Retrieve(Position P, HashTable H);
    12 HashTable Rehash(HashTable H);
    13 
    14 enum KindOfEntry {Legitimate, Empty, Deleted};
    15 struct HashEntry{
    16     ElementType Element;
    17     enum KindOfEntry Info;
    18 };
    19 typedef struct HashEntry Cell;
    20 
    21 struct HashTbl{
    22     int TableSize;
    23     Cell *TheCells;
    24 };

    初始化函数代码如下:

     1 HashTable InitializeTable(int TableSize){
     2     HashTable H;
     3     int i;
     4 
     5     if(TableSize < MinTableSize){
     6         printf("Table size too small
    ");
     7         return NULL;
     8     }
     9 
    10     H = malloc(sizeof(struct HashTbl));
    11     H->TableSize = NextPrime(TableSize);
    12     H->TheCells = malloc(H->TableSize * sizeof(Cell));
    13 
    14     for(i=0; i<H->TableSize; i++)
    15         H->TheCells[i].Info = Empty;
    16     
    17     return H;
    18 }

    Find函数实现代码如下:

     1 Position Find(ElementType Key, HashTable H){
     2     Position Pos;
     3     int i;
     4 
     5     i=0;
     6     Pos = Hash(Key, H->TableSize);
     7     while(H->TheCells[Pos].Info != Empty 
     8         && H->TheCells[Pos].Element != Key){
     9             Pos += (++i)*2-1;
    10             if(Pos >= H->TableSize)
    11                 Pos -= H->TableSize;
    12     }
    13     return Pos;
    14 }

    Insert函数代码实现如下:

    1 void Insert(ElementType Key, HashTable H){
    2     Position Pos;
    3     Pos = Find(Key, H);
    4     if(H->TheCells[Pos].Info != Legitimate){
    5         H->TheCells[Pos].Info = Legitimate;
    6         H->TheCells[Pos].Element = Key;
    7     }
    8 }

    Rehash函数代码实现如下:

     1 HashTable rehash(HashTable H){
     2     int i, OldSize = H->TableSize;
     3     HashTable OldH = H;
     4     Cell *OldCells = H->TheCells;
     5     
     6 
     7     H = InitializeTable(2*OldSize);
     8     for(int i=0; i<OldSize; i++){
     9         if(OldCells[i].Info == Legitimate)
    10             Insert(OldCells[i].Element, H);
    11     }
    12 
    13     free(OldH);
    14     free(OldCells);
    15     return H;
    16 }
  • 相关阅读:
    2021.1.20 学习总结
    2021.1.19 学习总结
    2021.1.18 学习总结
    学习总结13
    学习总结12
    学习总结11
    学习总结10
    ASP.NET网站开发步骤
    学习总结9
    阅读笔记4
  • 原文地址:https://www.cnblogs.com/lwyeah/p/8820437.html
Copyright © 2011-2022 走看看