您的位置:首页 > 其它

第11章 散列表

2015-08-03 10:40 225 查看
#include<stdio.h>
#include<stdlib.h>

unsigned int hashIndex1(const char *key, unsigned int tablesize)
{
unsigned int val = 0;
while (*key != '\0')
val += *key++;
return val%tablesize;
}
unsigned int hashIndex2(const char *key, unsigned int tablesize)
{
return (key[0] + 27 * key[1] + 729 * key[2]) % tablesize;
}
unsigned int hashIndex3(const char *key, unsigned int tablesize)
{
unsigned int val = 0;
while (*key != '\0')
val = (val << 5) + *key++;
return val%tablesize;
}
unsigned int hashIndex4(unsigned int key, unsigned int tablesize)
{
return key%tablesize;
}
struct ListNode{
int value;
ListNode* next;
};
struct HashTab{
int tablesize;
ListNode** list;
};
HashTab initializeTable(int tablesize)
{
HashTab h;
h.tablesize = tablesize;
h.list = (ListNode**)malloc(sizeof(ListNode*)*tablesize);
for (int i = 0; i < tablesize; ++i)
h.list[i] = NULL;
return h;
}
ListNode* FindHash(HashTab h, int key)
{
ListNode* L = h.list[ hashIndex4(key, h.tablesize) ];
while (L&&L->value != key) L = L->next;
return L;
}
void InsertHash(HashTab h, int key)
{
ListNode* p = FindHash(h, key);
if (p == NULL){
ListNode* newcell = (ListNode*)malloc(sizeof(ListNode));
newcell->next = NULL;
newcell->value = key;
//printf("%d\n", hashIndex4(key, h.tablesize));
int index = hashIndex4(key, h.tablesize);
if (h.list[index] == NULL) h.list[index] = newcell;
else{
newcell->next = h.list[index];
h.list[index] = newcell;
}
}
}

void printHash(HashTab h)
{
ListNode* tmp;
for (int i = 0; i < h.tablesize; ++i){
tmp = h.list[i];
while (tmp){
printf("%d\t", tmp->value);
tmp = tmp->next;
}
printf("\n");
}
}
int main()
{
int a[] = { 4, 2, 2, 0, 20, 11, 15, 18, 20, 13 };
HashTab h = initializeTable(5);
for (int i = 0; i < 10; ++i)
InsertHash(h, a[i]);
printHash(h);
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: