在教材中多爲第一種方法。實際上可以改變,減少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();
}
}