#ifndef _HASH_QUAD_H_ #define _HASH_QUAD_H_ typedef unsigned int Index; typedef Index Position; struct HashTbl; typedef struct HashTbl *HashTable; HashTable InitializeTable( int TableSize ); void DestoryTable( HashTable H ); Position Find( char *Key, HashTable H ); void Insert( char *Key, HashTable H ); #endif #include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <assert.h> #include <string.h> #include "oahash.h" enum KindOfEntry{ Legitimate, Empty, Delete }; struct HashEntry { char *Element; enum KindOfEntry Info; }; typedef struct HashEntry Cell; struct HashTbl { unsigned int TableSize; Cell *TheCells; }; int MinTableSize = 23; HashTable InitializeTable( int TableSize ) { HashTable H; unsigned int i; if ( TableSize < MinTableSize ) { printf("Table size too small/n"); return NULL; } H = malloc( sizeof( struct HashTbl ) ); if ( H == NULL ) return NULL; H->TableSize = TableSize; H->TheCells = malloc( sizeof( Cell ) * H->TableSize ); if ( H->TheCells == NULL ) { printf("no memory/n"); return NULL; } for( i = 0; i < H->TableSize; i++ ) { H->TheCells[i].Info = Empty; H->TheCells[i].Element = NULL; } return H; } int Hash( const char *Key, int TableSize ) { unsigned int HashVal = 0; while( *Key != '/0' ) { HashVal = ( HashVal << 5 ) + *Key++; } HashVal = HashVal % TableSize; return HashVal; } Position Find( char *Key, HashTable H ) { Position CurrentPos; int CollisionNum; CollisionNum = 0; CurrentPos = Hash( Key, H->TableSize ); while( H->TheCells[CurrentPos].Info != Empty && strcmp( H->TheCells[CurrentPos].Element, Key ) != 0 ) { CurrentPos += 2 * ++CollisionNum - 1; if ( CurrentPos >= H->TableSize ) { CurrentPos -= H->TableSize; } printf("-find-/n"); } return CurrentPos ; } void Insert( char *Key, HashTable H ) { Position Pos; Pos = Find( Key, H ); if ( H->TheCells[ Pos ].Info != Legitimate ) { H->TheCells[ Pos ].Info = Legitimate; H->TheCells[ Pos ].Element= malloc( sizeof(Key) ); if ( H->TheCells[ Pos ].Element == NULL ) { printf("no memory/n"); return; } strcpy( H->TheCells[ Pos ].Element, Key ); } } int main( int argc, char **argv ) { HashTable hash; unsigned int i; hash = InitializeTable( 27 ); Insert( "30", hash ); Insert( "40", hash ); Insert( "50", hash ); Insert( "60", hash ); Insert( "70", hash ); Insert( "80", hash ); Insert( "90", hash ); Insert( "91", hash ); Insert( "92", hash ); for ( i = 0; i < hash->TableSize; i++ ) { if ( hash->TheCells[ i ].Element ) { printf("--%d--%s--/n", i, hash->TheCells[i].Element ); } } return 0; }