Hashtable.h
#ifndef _hashtable_h_
#define _HASHTABLE_H_
#define MINTABLESIZE 10000
#define PRIME 10007
typedef unsigned int Index;
typedef Index Position;
struct HASHTBL;
typedef struct HASHTBL* HashTable;
typedef int ElementType;
typedef struct HASHENTRY Cell;
Enum Kindofentry {legitimate, empty,deleted};
HashTable initializetable (int tablesize);
void Destroytable (HashTable H);
Position Find (ElementType Key, HashTable H);
void Insert (ElementType Key, HashTable H);
ElementType Retrieve (Position p,hashtable H);
HashTable Rehash (HashTable H);
#endif
Hashtable.c
#include <stdio.h> #include <stdlib.h> #include "hashtable.h" struct Hashentry {ElementType Element;
Enum Kindofentry Info;
};
struct HASHTBL {int tablesize;
Cell *thecells;
};
int Hash (ElementType Key, int tablesize) {return key%tablesize;}
HashTable initializetable (int tablesize) {HashTable H;
int i;
if (Tablesize < mintablesize) {printf ("error!\n");
return NULL;
} H = (HashTable) malloc (sizeof (HASHTBL));
if (H = = NULL) {printf ("failure!\n");
Exit (Exit_failure);
} h->tablesize = Prime;//prime changes with tablesize H->thecells = (cell *) malloc (sizeof (cell) *h->tablesize);
if (h->thecells = = NULL) {printf ("failure!\n");
Exit (Exit_failure); for (i = 0; i < h->tablesize; i++) H->thecells[i].
Info = Empty;
return H;
} void Destroytable (HashTable h) {if (h) free (h->thecells);} Position Find (ElementType Key, HashTable H) {Position currentpos;
int collisionnum;
Collisionnum = 0;
Currentpos = Hash (Key, h->tablesize); while (H->thecells[currentpos). Info!= Empty && H->thecells[currentpos].
Element!= Key) {Currentpos + + 2 * ++collisionnum-1;
if (Currentpos >= h->tablesize) Currentpos-= h->tablesize;
return currentpos;
} void Insert (ElementType Key, HashTable H) {Position Pos;
Pos = Find (Key, H); if (H->thecells[pos). Info!= legitimate) {H->thecells[pos].
Info = legitimate; H->thecells[pos].
Element = Key; } ElementType Retrieve (Position P, HashTable h) {if (H && h->thecells[p]. Info==legitimate) return h->thecells[p].
Element;
else return 0;
} HashTable Rehash (HashTable H) {int i, oldsize;
Cell *oldcells;
Oldcells = h->thecells;
Oldsize = h->tablesize; H = initializetable (2 * OldSize); for (i = 0; i < oldsize i++) if (oldcell[i). Info = = legitimate) Insert (Oldcells[i].
Element, H);
Free (oldcells);
return H; }