在教材中多为第一种方法。实际上可以改变,减少h->tablesize次的malloc()操作
下面是依次是声明、方法一、方法二:
typedef int ElementType; /* hashSep.h */ #ifndef HashSep_H #define HashSep_H typedef unsigned int Index; //Hash()散列函数的返回类型 struct listnode; typedef struct listnode *position; typedef struct listnode *list; struct hashta1; typedef struct hashta1 *hashtable; list MakeEmpty(void); hashtable InitTable_1(int tableSize); //一个不太好的初始化程序 hashtable InitTable_2(int tableSize); //一个比较好的初始化程序 void DestoryTable(hashtable h); position Find(ElementType key, hashtable h); void Insert(ElementType key, hashtable h); ElementType Retrieve(position p); #endif /* ENDING */ /* hashSep.c */ /* The list using headers */ #include<stdio.h> #include<stdlib.h> #define MinTableSize (5) struct listnode { ElementType element; position next; }; struct hashta1 { int tableSize; list *theLists; // 指向指针的指针 };
hashtable InitTable_1(int tableSize) { hashtable h; int i; if (tableSize < MinTableSize) { printf("Table size too small!!\n"); return NULL; } /* allocate tabel */ h = malloc(sizeof(struct hashta1)); if (h == NULL) { printf("Out of space!!\n"); exit(1); } h->tableSize =NextPrime(tableSize); /* allocate array of lists */ h->theLists = malloc(sizeof(list)*h->tableSize); //本方法中,存放的是多个headers指针,不是listnode结构体,故下面要有 h->tableSize次调用malloc函数为数组中的每个指针赋值 if(h->theLists==NULL) { printf("Out of space!!\n"); exit(1); } /* allocate list header */ for (i = 0;i < h->tableSize;++i) { h->theLists[i] = malloc(sizeof(struct listnode)); if (h->theLists[i] == NULL) { printf("Out of space!!\n"); exit(1); } else h->theLists[i]->next= NULL; } return h; }hashtable InitTable_2(int tableSize) { hashtable h; int i; if (tableSize < MinTableSize) { printf("Table size too small!\n"); return NULL; } /* allocate table */ h = malloc(sizeof(struct hashta1)); if (h == NULL) { printf("Out of space!!\n"); exit(1); } h->tableSize = NextPrime(tableSize); /* allocate array of list */ h->theLists = malloc(sizeof(struct listnode)*h->tableSize); //避免了调用h->tableSize次的malloc()为h->theLists[i]赋值,降低时间复杂度 if (h->theLists == NULL) { printf("Out of space!!\n"); exit(1); } /* allocate list header */ for (i = 0;i < h->tableSize;++i) { h->theLists[i]->next= MakeEmpty(); } }