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<stdio.h>
#include<stdlib.h>
#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("\n\n");
	
}

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("error\n");
		exit(1);
	}
}

在这里插入图片描述
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值