栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c语言 hash表

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c语言 hash表

先存着,c语言真就啥都没有呗

struct hashTable {
    int key;
    UT_hash_handle hh;
};

bool containsDuplicate(int* nums, int numsSize) {
    struct hashTable* set = NULL;
    for (int i = 0; i < numsSize; i++) {
        struct hashTable* tmp;
        HASH_FIND_INT(set, nums + i, tmp);
        if (tmp == NULL) {
            tmp = malloc(sizeof(struct hashTable));
            tmp->key = nums[i];
            HASH_ADD_INT(set, key, tmp);
        } else {
            return true;
        }
    }
    return false;
}

作者:LeetCode-Solution
链接:https://leetcode.cn/problems/contains-duplicate/solution/cun-zai-zhong-fu-yuan-su-by-leetcode-sol-iedd/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

实现hashtable,大概写了下int类型的,,大概思路就是一个指针p指向一块内存,
这块内存有若干指针,分别指向一个链表,链表在hash碰撞的时候增加节点,牺牲内存增加速度

#include
#include
#define max_len 50
#define GET_KEY(num) (num)%max_len
typedef struct hashnode {
	struct hashnode* next;
	int value;
	int count;
}Hashnode;
void init(Hashnode** hashtable, int size);
void display(Hashnode** hashtable, int size);
void find(Hashnode** hashtable, int size, int num);
void test_null(Hashnode* p);

void main() {
	int num[max_len * 2];
	for (int i = 0; i < max_len * 2; i++) {
		num[i] = i + max_len;
		printf("%d ", num[i]);
	}
	printf("n");
	Hashnode** hashtable = (Hashnode**)malloc(max_len * 8 + 8);
	test_null(hashtable);
	init(hashtable, max_len);
	num[98] = 50;
	for (int i = 0; i < max_len * 2; i++) {
		find(hashtable, max_len, num[i]);
	}
	display(hashtable, max_len);

}

void init(Hashnode** hashtable, int size) {
	Hashnode** p = hashtable;
	for (int i = 0; i < size; i++) {;
		(*p)= (Hashnode*)malloc(16);
		test_null(*p);
		(*p)->next = NULL;
		(*p)->value = -1;
		(*p)->count = 0;
		p++;
	}
}

void display(Hashnode** hashtable, int size) {
	for (int i = 0; i < size; i++) {
		Hashnode* p = *(hashtable + i);
		while (p) {
			printf("%d %d ", p->value, p->count);
			p = p->next;
		}
		printf("n");
	}
	printf("nn");
	
}

void find(Hashnode** hashtable, int size,int num) {
	int pos = GET_KEY(num),flag=0;
	Hashnode* p = *(hashtable + pos),*q=p;
	while (p) {
		if (p->value == -1) {
			p->value = num;
			p->count++;
			flag = 1;
			break;
		}
		if (p->value == num) {
			p->count++;
			flag = 1;
			break;
		}
		else {
			q = p;
			p = p->next;
		}
	}
	if (!flag) {
		Hashnode* node = (Hashnode*)malloc(16);
		test_null(node);
		node->value = num;
		node->next = NULL;
		node->count = 1;
		q->next = node;
	}
}
//vs还是会有没检查内存的警告,不知道是这么写有问题还是vs检查不到
void test_null(Hashnode* p) {
	if (!p) {
		printf("errorn");
		exit(1);
	}
}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1008457.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号