数据结构哈希用法

本文将介绍数据结构中的哈希,哈希由hash与chunk组成

哈希数据存储的数量为一组hash的数据×chunk的大小:HASH_NUM * CHUNK_NUM

下面从哈希的结构、初始化、创建、增、删、遍历、释放用法进行代码梳理

1.哈希的结构

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

typedef struct node{
  int data;             //用于存数据
  struct node *next;    //用于存指针
} hash_t;

2.定义与声明

#define HASH_NUM 4096
#define CHUNK_NUM 1024

3.哈希的初始化:

初始化一组hash和chunk

void hashInit(){

    //1.初始化哈希
    hash_t **h = (hash_t **)malloc(HASH_NUM * CHUNK_NUM);
    int i = 0;
    for(i = 0; i < HASH_NUM; i++){

        //2.初始化chunk
        h[i] = (struct node *)malloc(sizeof(struct node));
        h[i]->next = NULL;
    }   
}

4.哈希插入:

计算出key值,再创建一个点,再插入数据

void hashInsertNode(hash_t **h, int data)
{
    int key = data % HASH_NUM; 
    struct node * p = h[key];
    //从头插入数据
    struct node * temp;
    temp = (struct node *)malloc(sizeof(struct node));
    temp->data = data;
    temp->next = p->next;
    p->next = temp;
}

5.哈希查找:

计算出key值,while循环找到对应的数据

int hashFindNode(hash_t **h, int data)
{
    int key = data % HASH_NUM; //得到key值
    struct node *p = h[key]; //找到对应链表
				
    //对比要查找的数据
    while (p->next != NULL )
    {
	    if (p->next->data == data)
	    {	
                //找到返回1
                return 1;
	    }
	    p = p->next;
    }
    //没有找到返回0
    return 0;
}

6.哈希的遍历打印

int travelHash(struct node *head)
{

    if (head->next == NULL)
    {
    	return -1;
    }
    //遍历链表,打印数据
    while(head->next != NULL)
    {
    	head = head->next;
    	printf("%d ", head->data);
    }
    putchar(10);
    return 0;
}

 7.哈希释放:

先遍历释放每个点,再释放整个hash

int freeHashData(struct node *head)
{
    //如果链表后面没有数据,则不需要释放
    if (head->next == NULL)
    {
    	return 0;
    }  	
    while(head->next != NULL)
    {       
	    struct node *temp = head->next;
	    head->next = head->next->next;
	    free(temp);
	    temp = NULL;
    }
    return 0;
}

//释放整个哈希
free(h);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值