哈希表

#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 *str, Node *head) {
	Node *p = (Node *)malloc(sizeof(Node));
	p->str = strdup(str);
	p->next = head;
	return p;
}

HashTable *init_hashtable(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 *node) {
	if (!node) return;
	Node *p = node, *q;
	while (p) {
		q = p->next;
		free(p->str);
		free(p);
		p = q;
	}
	free(q);
	return ;
}

void clear_hashtable(HashTable *h) {
	if (!h) 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] = {0};
	HashTable *h = init_hashtable(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;
		}
	}
#undef max_n
	clear_hashtable(h);
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值