#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node {
char *data;
struct Node *next;
} Node;
typedef struct hash_table {
Node **data;
int size;
} hash_table;
hash_table *init_hashtable (int size) {
hash_table * hash = (hash_table *)malloc(sizeof(hash_table));
hash->size = size << 1;
hash->data = (Node **)calloc(hash->size, sizeof(Node *));
return hash;
}
void clear_node(Node *p) {
if (!p) return ;
Node *q;
while(p) {
q = p->next;
free(p->data);
free(p);
p = q;
}
return ;
}
void clear(hash_table *p) {
if (!p) return ;
for (int i = 0; i < p->size; i++) clear_node(p->data[i]);
free(p->data);
free(p);
return ;
}
Node *init(char *s, Node *p) {
Node *q = (Node *)malloc(sizeof(Node));
q->next = p;
q->data = strdup(s);
return q;
}
int BKDRhash(char *s) {
int seed = 31, hash = 0;
for(int i = 0; s[i]; i++) hash = hash * seed + s[i];
return hash & 0x7ffffff;
}
int seach(char *s, hash_table *p) {
int ind = BKDRhash(s) % p->size;
Node *node = p->data[ind];
while(node && strcmp(node->data, s)) node = node->next;
if (!node) return -1;
return ind;
}
void insert(hash_table *p, char *s) {
if (!p) return ;
int ind = BKDRhash(s) % p->size;
p->data[ind] = init(s, p->data[ind]);
}
int main() {
int op;
#define MAX_N 5
char s[MAX_N + 5];
hash_table *hash = init_hashtable(MAX_N);
for(int i = 0; i < MAX_N; i++)
while (~scanf("%d%s", &op, s))
switch (op) {
case 1: printf("%s insert hashtable
", s); insert(hash, s); break;
case 0: printf("%s seach %d
", s, seach(s, hash));
}
#undef MAX_N
return 0;
}