以下是我用c语言实现数据结构中的哈希表#pragma once;
#ifndef _STDLIB_H
#define _STDLIB_H
#include
#include
#include
#endif
#ifndef _DEBUG_H
#define _DEBUG_H
#include
#endif
#define HASHTABLESIZE 100
typedef int KeyType;
#define ERROR INT_MAX
#ifndef _ELEMTYPE_H
#define _ELEMTYPE_H
typedef struct
{
int Num;
std::string Name;
int Age;
std::string Sex;
}ElemType,*Node,HashNode;
#endif
#ifndef _FUNCTION_H
#define _FUNCTION_H
typedef void(*Function)(ElemType);
#endif
#ifndef _HASHTABLE_H
#define _HASHTABLE_H
typedef struct
{
ElemType elem[HASHTABLESIZE]; //ù·
int Count; //±°
int SizeIndex; //±í
}*HashTable,Size;
#endif
#pragma once;
#include "stdafx.h"
bool InitHashTable(HashTable &HT);
int Hash(KeyType K);
bool HashTableInsert(HashTable &HT, ElemType & Type);
bool HashTableDelete(HashTable &HT, KeyType Type);
ElemType HashTableSearch(HashTable &HT, KeyType Type);
void HashTableTraverse(HashTable &HT,Function p_function);
#include "HashTable.h"
bool InitHashTable(HashTable &HT)
{
if (HT->elem == NULL)
return false;
else
{
int i;
for (i = 0; i
{
HT->elem[i].Num = 0;
HT->elem[i].Name = "0";
HT->elem[i].Age = 0;
HT->elem[i].Sex = "0";
}
HT->SizeIndex = HASHTABLESIZE;
HT->Count = 0;
return true;
}
}
int Hash(KeyType K)
{
if (K <= 100)
return K - 1;
else
return ERROR;
}
bool HashTableInsert(HashTable &HT, ElemType & Type)
{
if (HT->elem == NULL)
return false;
else
{
KeyType Key = Hash(Type.Num);
if (Key == ERROR)
return false;
HT->elem[Key].Num = Type.Num;
HT->elem[Key].Name = Type.Name;
HT->elem[Key].Age = Type.Age;
HT->elem[Key].Sex = Type.Sex;
HT->Count++;
return true;
}
}
bool HashTableDelete(HashTable &HT, KeyType Type)
{
if (HT->elem == NULL)
return false;
else
{
KeyType Key = Hash(Type);
if (Key == ERROR)
return false;
else
{
HT->elem[Key].Num = 0;
HT->elem[Key].Name = NULL;
HT->elem[Key].Age = 0;
HT->elem[Key].Sex = NULL;
HT->Count--;
}
return true;
}
}
ElemType HashTableSearch(HashTable &HT, KeyType Type)
{
if (HT->elem == NULL)
return HT->elem[0];
else
{
KeyType Key = Hash(Type);
if (Key == ERROR)
return HT->elem[0];
else
{
return HT->elem[Key];
}
}
}
void HashTableTraverse(HashTable &HT, Function p_function)
{
if (HT->elem == NULL)
return;
else
{
int i;
for (i = 0; i SizeIndex; i++)
{
if (HT->elem[i].Name == NULL)
continue;
(*p_function)(HT->elem[i]);
}
}
}