1034: 散列表(2)
Description
已知Hash表的表长MaxSize为11,Hash函数为HashFunc(k)=k%11,冲突处理方法为链地址法,部分代码如下,勿改动。请补充完成成员函数HashSearch,该函数的功能是动态查找k,若查找失败,则插入k,并返回查找失败所需的比较次数,若查找成功,返回查找k所需的比较次数。
#include<iostream>
using namespace std;
const int MaxSize=11; //maxsize
struct Node
{
int data;
Node *next;
};
class LinkHash
{
public:
LinkHash(); //initialize an empty list
int HashFunc(int k); //hash function
int HashSearch(int k); //dynamic search k
void Display();
private:
Node *ht[MaxSize]; //ht数组用来保留各个链表的头指针
};
//hash function
int LinkHash::HashFunc(int k)
{
return k%11; //hash函数,假设为除余法,余数为11
}
//constructor:initialize an empty hashlist
LinkHash::LinkHash()
{
int i;
for(i=0;i<MaxSize;i++)
ht[i]=nullptr; //empty pointer
}
void LinkHash::Display()
{
int i;
for(i=0;i<MaxSize;i++)
{
cout<<"Hash address:"<<i<<",value:";
Node *p;
for(p=ht[i];p!=nullptr;p=p->next)
cout<<p->data<<" ";
cout<<endl;
}
}
//在下面补充实现动态查找算法
int main()
{
LinkHash LS;
int k;
while(1)
{
cin>>k;
if(!k) break;
try{
LS.HashSearch(k);
// LS.Display();
}
catch(const char *ms)
{
cout<<ms<<endl;
}
}
LS.Display();
return 0;
}
Input
Output
Sample Input
47 7 29 11 16 92 22 8 3 29 0
Sample Output
Hash address:0,value:22 11
Hash address:1,value:
Hash address:2,value:
Hash address:3,value:3 47
Hash address:4,value:92
Hash address:5,value:16
Hash address:6,value:
Hash address:7,value:29 7
Hash address:8,value:8
Hash address:9,value:
Hash address:10,value:
//
// Created by Legends丶Hu on 2020/2/6.
//
#include<iostream>
using namespace std;
const int MaxSize = 11; //maxsize
struct Node {
int data;
Node *next;
};
class LinkHash {
public:
LinkHash(); //initialize an empty list
int HashFunc(int k); //hash function
int HashSearch(int k); //dynamic search k
void Display();
private:
Node *ht[MaxSize]; //ht数组用来保留各个链表的头指针
};
//hash function
int LinkHash::HashFunc(int k) {
return k % 11; //hash函数,假设为除余法,余数为11
}
//constructor:initialize an empty hashlist
LinkHash::LinkHash() {
int i;
for (i = 0; i < MaxSize; i++)
ht[i] = NULL; //NULL is empty
}
void LinkHash::Display() {
int i;
for (i = 0; i < MaxSize; i++) {
cout << "Hash address:" << i << ",value:";
Node *p;
for (p = ht[i]; p; p = p->next)
cout << p->data << " ";
cout << endl;
}
}
int LinkHash::HashSearch(int k) {
int j = HashFunc(k);
Node *p = ht[j];
while(p && p->data != k) {
p = p->next;
}
if(p && p->data == k) return 1;
else {
Node *s = new Node;
s->data = k;
s->next = ht[j];
ht[j] = s;
}
return 0;
}
int main() {
LinkHash LS;
int k;
while (1) {
cin >> k;
if (!k) break;
try {
LS.HashSearch(k);
// LS.Display();
}
catch (const char *ms) {
cout << ms << endl;
}
}
LS.Display();
return 0;
}
本文介绍了一种基于链地址法解决散列冲突的方法,并提供了一个具体的C++实现案例。该案例展示了如何构造一个散列表,包括散列函数的设计、散列表的初始化、元素的动态查找及插入操作。
752

被折叠的 条评论
为什么被折叠?



