数据结构头歌:散列——实验及提升训练(带超全注释+源代码)

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

/*哈希结构*/
struct hashTable
{
  int *element;//存放键值的连续空间起始地址
  int maxNum;// 哈希表长度 
  int curNum;//当前哈希表已有数据元素 
};

struct node
{
  int data ;
  struct node *next;
};

struct hashTable_link
{
  struct node *element;
  int maxNum;// 哈希表长度  
};

/*第一关*/
//初始化一个哈希表,能满足线性探测再散列处理冲突法使用,初始化哈希表元素均为-1,表示该位置为空,可插入
  struct hashTable* initHashTable_linear()
{
  struct hashTable *h=(struct hashTable *)malloc(sizeof(struct hashTable));
  h->maxNum=10;
  h->curNum=0;
  h->element=(int *)malloc(sizeof(int)*h->maxNum);
  for(int i=0;i<h->maxNum;i++){
    h->element[i]=-1;
  }
  return h;
 
}
 

//初始化一个哈希表,能满足拉链法处理冲突法使用。初始化哈希表元素为0,用于计算该条链中数据个数,在插入时增加
struct hashTable_link * initHashTable_link()
{
  struct hashTable_link *h1=(struct hashTable_link *)malloc(sizeof(struct hashTable_link));
  h1->maxNum=10;
  struct node *p=(struct node *)malloc(sizeof(struct node));
  h1->element=(struct node *)malloc(sizeof(struct node));
  for(int i=0;i<h1->maxNum;i++)
  {
    p->data=0;
    p->next=NULL;
    h1->element[i]=*p;    
  }
  return h1;
}

/*第二关*/
//输出线性探测再散列法构建的哈希表,从下标为0的元素开始输出,每输出一个数据空一格
void printHashTable(struct hashTable *h)
{
  for(int i=0;i<h->maxNum;i++)
   printf("%d ",h->element[i]);
 
}
/*第三关*/
//哈希函数,h(key) = (key*3) %  7
int hashFun(int key)
{
  return (key*3) %  7;
}
 
//函数功能:计算key的哈希地址,若发生冲突,则使用线性探测再散列的方法查找合适的插入位置下标,并返回该下标
int findPos(struct hashTable *h , int key)
{
  int keyvalue=hashFun(key);
  if(h->element[keyvalue]==-1){
    return keyvalue;
  }
  else{
    while(1){
      keyvalue++;
      if(keyvalue==h->maxNum) keyvalue=0;
      if(h->element[keyvalue]==-1){
       return keyvalue;
      }
    }
  }
 
}
 
//插入键值函数,若哈希表空间已满,则返回-1,否则返回插入位置下标
int insertKey(struct hashTable *h , int key)
{
  if(h->curNum==h->maxNum) return -1;
  int keyid=findPos(h,key);
  h->element[keyid]=key;
  return keyid;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值