- 头文件中的原始定义
#ifndef _HelpSep_H
#define MinTableSize 1
typedef char *ElementType;
struct ListNode;
typedef struct ListNode *Position;
struct Hashtbl;
typedef struct HashTbl *HashTable;
HashTable initializeTable(int TableSize);
Position Find(ElementType key, HashTable H);
void Insert(ElementType key, HashTable H);
#endif // !_HelpSep_H
#pragma once
- 主函数
#include<string.h>
#include <stdio.h>
#include <time.h>
#include "malloc.h"
#include "hashHelp.h"
#define _CRT_SECURE_NO_DEPRECATE
#define _CRT_SECURE_NO_WARNINGS
// 定义散列函数的返回值
typedef unsigned int Index;
struct ListNode {
ElementType element;
Position next;
};
typedef Position List;
struct HashTbl {
int TableSize;
List *TheLists;
};
// 散列函数
Index Hash(const char *key, int tableSize);
int NextPrime(int tableSize);
int main()
{
printf("\r\n函数开始运行!\r\n");
HashTable hashTable = initializeTable(7);
Insert("nihao", hashTable);
Insert("nihao", hashTable);
Insert("nihao", hashTable);
Insert("hello", hashTable);
Insert("hello", hashTable);
Insert("hello", hashTable);
Insert("hello", hashTable);
Insert("byebye", hashTable);
Insert("byebye", hashTable);
Insert("byebye", hashTable);
Insert("yu", hashTable);
Position node = Find("hello", hashTable);
printf("\n node = %s", node->element);
printf("\r\n函数结束运行!\r\n");
getchar();
//return 0;
}
// 一个好的散列函数:1)在散列表中均匀分配; 2)计算速度快
Index Hash(const char *key, int tableSize) {
unsigned int hashVal = 0;
while (*key != '\0') {
hashVal = (hashVal << 5) + *key++;
}
return hashVal % tableSize;
}
// 这个函数待完善:产生一个素数
int NextPrime(int tableSize)
{
return 7;
}
HashTable initializeTable(int tableSize)
{
HashTable H; // 注意H是一个指针
int i;
if (tableSize < MinTableSize) {
printf("Table size too small!");
return NULL;
}
H = (HashTable)malloc(sizeof(struct HashTbl));
if (H == NULL) {
printf("Out of space!");
return NULL;
}
H->TableSize = NextPrime(tableSize);
H->TheLists = (List *)malloc(sizeof(List) * H->TableSize);
if (H->TheLists == NULL) {
printf("Out of space!");
return NULL;
}
for (i = 0; i < H->TableSize; i++) {
H->TheLists[i] = (Position)malloc(sizeof(struct ListNode));
if (H->TheLists[i] == NULL) {
printf("Out of space!");
return NULL;
} else {
H->TheLists[i]->next = NULL;
}
}
printf("\n初始化表成功!\n");
return H;
}
Position Find(ElementType key, HashTable H)
{
Position P;
List L;
L = H->TheLists[Hash(key, H->TableSize)];
P = L->next;
// 这个地方要改为strcmp
while (P != NULL && 0 != strcmp(P->element, key)) {
P = P->next;
}
return P;
}
void Insert(ElementType key, HashTable H)
{
Position pos, newcell;
List L;
pos = Find(key, H);
if (pos == NULL) {
newcell = (Position)malloc(sizeof(struct ListNode));
if (newcell == NULL) {
printf("Out of space!");
} else {
L = H->TheLists[Hash(key, H->TableSize)];
newcell->next = L->next;
newcell->element = key;
L->next = newcell;
}
}
}
运行结果: