散列 - 数据结构 (分离链接法、开放定址法)

本文介绍了散列作为数据结构的基本概念,以及解决冲突的两种主要方法:分离链接法和开放定址法。分离链接法通过链表处理冲突,而开放定址法则包括线性探测、平方探测等策略。平方探测法在表大小为素数时能有效避免冲突,但当表填充超过一半时可能面临插入失败的问题。
摘要由CSDN通过智能技术生成

        散列是一种用于以常数平均时间执行插入、删除和查找的技术。理想的散列数据结构只不过是一个包含有关键字的具有固定大小的数组。典型情况下,一个关键字就是一个

带有相关值(工资信息等)的字符串。

        散列函数主要的问题就是解决冲突的消除问题。如果当一个元素被插入时另一个元素已经存在(散列值存在),那么就会产生冲突。解决这种冲突的方法有几种,一般用最

简单的两种:分离链接法、开放地址法

        1.分离链接法



//分离链接散列表的头文件声明

#ifndef HASH_H_INCLUDED
#define HASH_H_INCLUDED

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

typedef unsigned int Index;
typedef int DataType;
struct ListNode;
typedef struct ListNode *Position;
typedef Position List;
struct HashTbl;
typedef struct HashTbl *HashTable;


HashTable Hash_InitTable(int TableSize);
void Hash_Insert(DataType key, HashTable H);
void Hash_Delete(DataType key, HashTable H);
void Hash_Show(HashTable H);
int Hash_Free(HashTable H);

#endif // HASH_H_INCLUDED

//分离链接散列表的功能函数声明

#include "hash.h"

struct ListNode
{
    DataType Data;
    Position Next;
};

struct HashTbl
{
    int TableSize;
    List *TheLists;
};

void Print_Err(char *str);
int NextPrime(int n);

Index Hash(const int key, int tablesize)
{
    unsigned int hashval = 0;
    int x;

    x = key;
    if(x < 0)
    {
        printf("the key is low 0\n");
        exit(-1);
    }
    while(x != 0)
    {
        hashval = (hashval << 3) + x%10;
        x /= 10;
    }

    return hashval % tablesize;
}

HashTable Hash_InitTable(int Size)
{
    HashTable H;
    int i;

    H = (HashTable)malloc(sizeof(struct HashTbl));
    if(H == NULL)
        Print_Err("no space for malloc H");

    H->TableSize = NextPrime(Size);
    H->TheLists = (List *)malloc(sizeof(List) * H->TableSize);
    if(H->TheLists == NULL)
        Print_Err("no space for malloc H->TabLists");

    for(i = 0; i < H->TableSize; i++)
    {
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值