哈希表:
使用哈希函数将任意类型的数据映射为整型值
比如val % size这个函数,(处理冲突)如下图所示:
处理冲突的四大类操作:
1.开放定址法
2.拉链法
3.再哈希
4.建立公共溢出区(存储产生冲突的值的索引)
Leetcode题:
代码实现:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node{
char *str;
struct Node *next;
}Node;
typedef struct HashTable{
Node **data;
int size;
}HashTable;
Node *init_node(char *s, Node *head){
Node *p = (Node *)malloc(sizeof(Node));
p->str = strdup(s);//使用头插法
p->next = head;
return p;
}
HashTable *init_table(int n){
HashTable *h = (HashTable *)malloc(sizeof(HashTable));
h->size = n << 1;
h->data = (Node **)calloc(h->size, sizeof(Node *));
return h;
}
int BKDRHash(char *s){
int seed = 31, hash = 0;
for(int i = 0; s[i]; i++) hash = hash * seed + s[i];
return hash & 0x7fffffff;
}
int insert(HashTable *h, char *str){
int hash = BKDRHash(str);
int ind = hash % h->size;
h->data[ind] = init_node(str, h->data[ind]);
return 1;
}
int search(HashTable *h, char *str){
int hash = BKDRHash(str);
int ind = hash % h->size;
Node *p = h->data[ind];
while(p && strcmp(p->str, str)) p = p->next;
return p != NULL;
}
void clear_node(Node *node){
if(node == NULL) return;
Node *p = node, *q;
while(p){
q = p->next;
free(p->str);
free(p);
p = q;
}
free(q);
return;
}
void clear_table(HashTable *h){
if(h == NULL) return;
for(int i = 0; i < h->size; i++) clear_node(h->data[i]);
free(h->data);
free(h);
return;
}
int main(){
int op;
#define max_n 100
char str[max_n + 5];
HashTable *h = init_table(max_n + 5);
while(~scanf("%d%s", &op, str)){
switch (op){
case 0:
printf("insert %s to hash table\n", str);
insert(h, str);
break;
case 1:
printf("search %s from hash table result = %d\n", str, search(h, str));
break;
}
}
clear_table(h);
return 0;
}