哈希,链接法解决冲突

#include<iostream>
using namespace std;

struct ListNode;
typedef struct ListNode *Position;
struct Hash_table;
typedef Hash_table *Hashtab;
typedef Position List;

#define Min_table_size 10

struct ListNode
{
 int Emelent;
 Position Next;
};

struct Hash_table
{
 int Table_size;
 List *Thelist;//指向链表的链表
};

//相关函数声明//
Hashtab Inittable(int Table_size);     //初始化一个散列
Position Find(int x, Hashtab H);      //查找元素x,返回对应的位置
int Hash(int x);  //散列函数
void Insert(int Key, Hashtab H);   //在散列中插入元素Key
void Delete(int Key, Hashtab H);   //在散列中删除元素Key

 

///相关函数定义
Hashtab Inittable(int table_size)
{
 Hashtab H;
 if (table_size < Min_table_size)
 {
  cout << "Table size is too small" << endl;
  return NULL;
 }

 H = (Hashtab)malloc(sizeof(Hash_table));
 if (H == NULL)  cout << "out of space" << endl;
 H->Table_size = table_size;
 H->Thelist = (List*)malloc(sizeof(Position) * H->Table_size);//不知道Position里头有多少个元素也可以分配内存吗
 if (H->Thelist == NULL) cout << "out of space" << endl;
 for (int i = 0; i != H->Table_size; ++i)
 {
  H->Thelist[i] = (Position)malloc(sizeof(ListNode));
  if (H->Thelist[i] == NULL) cout << "out of space" << endl;
  else
  {
   H->Thelist[i]->Emelent = i;
   H->Thelist[i]->Next = NULL;
  }
 }
 return H;
}

int Hash(int x)   //对10取余数
{
 return x % 10;
}

Position Find(int x, Hashtab H)
{
 Position P;
 List L;

 L = H->Thelist[Hash(x)];  //指向含有那个元素的表头
 P = L->Next;
 while (P != NULL && P->Emelent != x)
  P = P->Next;
 return P;
}

void Insert(int Key, Hashtab H)
{
 Position Pos, Newcell;
 List L;
 Pos = Find(Key, H);  //先找找看,有没有Key,有就算了
 if (Pos == NULL)
 {
  Newcell = (Position)malloc(sizeof(ListNode));
  if (Newcell == NULL)  cout << "out of space" << endl;
  else    //插入到槽后面的第一个位置
  {
   L = H->Thelist[Hash(Key)];
   Newcell->Next = L->Next;
   Newcell->Emelent = Key;
   L->Next = Newcell;
  }
 }
}

void Delete(int Key, Hashtab H)
{
 Position p, Tmpcell;
 List L;
 p = Find(Key, H);
 if (p == NULL)
  cout << "not find the " << Key << endl;
 else
 {
  L = H->Thelist[Hash(Key)];
  p = L;
  while (p->Next != NULL && p->Next->Emelent != Key)   //寻找Key的前驱节点
  {
   p = p->Next;
  }
  //
  Tmpcell = p->Next;
  p->Next = Tmpcell->Next;
  free(Tmpcell);
 }

}
int main()
{
 Hashtab H = Inittable(11);
 cout << H->Thelist[9]->Emelent << endl;
 Insert(1, H);
 Insert(4, H);
 Insert(9, H);
 Insert(16, H);
 Insert(25, H);
 Insert(19, H);
 Insert(29, H);
 Delete(19, H);
 
 cout << H->Thelist[9]->Next->Next->Emelent << endl;
 return 0;
}

转载于:https://www.cnblogs.com/Rakint/p/9795428.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值