#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_N 10000
char str[MAX_N + 5] = {0};
typedef struct Node {
char* str;
struct Node* next;
}Node;
typedef struct HashTable {
Node** data;
int size;
}HashTable;
Node* init_Node(char* str, Node* head) {
Node* p = (Node*)malloc(sizeof(Node));
p->str = _strdup(str);
p->next = head;
return p;
}
HashTable* init_hash(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* str) {
int seed = 31, hash = 0;
for (int i = 0; str[i]; i++) {
hash = hash * seed + str[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* head) {
if (head == NULL) return;
Node* p = head, * q;
while (p != NULL) {
q = p->next;
free(q);
p = q;
}
return;
}
void clear(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() {
HashTable* h = init_hash(MAX_N);
int op;
while (~scanf("%d%s", &op, str)) {
switch (op) {
case 0 :
printf("insert %s to HashTable\n", str);
insert(h, str);
break;
case 1:
printf("search %s from HashTable result = %d \n", str, search(h, str));
break;
}
}
#undef MAX_N
clear(h);
return 0;
}