4.Hash

本文介绍了使用C语言编写的哈希表实现,包括hash.h中的数据结构定义、hash_create函数创建哈希表、hash_insert用于插入键值对以及hash_search进行查找功能。通过demo.c展示了如何在主程序中使用这些函数进行操作。
摘要由CSDN通过智能技术生成

hash.h

#ifndef _HASH_
#define _HAHS_

#define N 15
typedef int datatype;

typedef struct node
{
	datatype key;
	datatype value;
	struct node *next;
} listnode, *linklist;

typedef struct
{
	listnode data[N];
} hash;

hash *hash_create();
int hash_insert(hash *HT, datatype key);
linklist hash_search(hash *HT, datatype key);

#endif

hash.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hash.h"

hash *hash_create()
{
	hash *HT;
	if ((HT = (hash *)malloc(sizeof(hash))) == NULL)
	{
		printf("malloc failed\n");
		return NULL;
	}
	memset(HT, 0, sizeof(hash));

	return HT;
}

int hash_insert(hash *HT, datatype key)
{
	if (HT == NULL)
	{
		printf("HT is null\n");
		return -1;
	}
	linklist p, q;
	if ((p = (linklist)malloc(sizeof(listnode))) == NULL)
	{
		printf("malloc failed\n");
		return -1;
	}
	p->key = key;
	p->value = key % N;
	p->next = NULL;

	q = &(HT->data[key % N]);
	while (q->next && q->next->key < p->key)
	{
		q = q->next;
	}
	p->next = q->next;
	q->next = p;
	return 0;
}

linklist hash_search(hash *HT, datatype key)
{
	if (HT == NULL)
	{
		printf("HT is null\n");
		return NULL;
	}
	linklist p;
	p = &(HT->data[key % N]);
	while (p->next && p->next->key != key)
	{
		p = p->next;
	}
	if (p->next == NULL)
	{
		return NULL;
	}
	else
	{
		printf("found\n");
		return p->next;
	}
	return p;
}

demo.c

#include <stdio.h>
#include <stdlib.h>
#include "hash.h"

int main()
{
	hash *HT;
	int data[] = {23, 34, 14, 38, 46, 16, 68, 104, 72, 25};
	int i, key;
	linklist r;
	if ((HT = hash_create()) == NULL)
	{
		return -1;
	}
	for (i = 0; i < sizeof(data) / sizeof(int); i++)
	{
		hash_insert(HT, data[i]);
	}
	printf("input:\n");
	scanf("%d", &key);
	r = hash_search(HT, key);
	if (r == NULL)
	{
		printf("not found\n");
	}
	else
	{
		printf("index:%d %d %d\n", key, r->key, r->value);
	}
	return 0;
}

makefile

CC = gcc

SRC = $(wildcard *.c)
OBJ = $(patsubst %.c, %.o, $(SRC))

test:$(SRC)
	$(CC)	$^	-o	$@	-Wall


.PHONY:clean
clean:
	rm	./*.o

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值