题目描述

已知Hash表的表长MaxSize为11,Hash函数为HashFunc(k)=k%11,冲突处理方法为链地址法,部分代码如下,勿改动。请补充完成成员函数HashSearch,该函数的功能是动态查找k,若查找失败,则插入k,并返回查找失败所需的比较次数,若查找成功,返回查找k所需的比较次数。
#include
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 ht[i]=nullptr; //empty pointer
}
void LinkHash::Display()
{
int i;
for(i=0;i {
cout<<”Hash address:”< Node p;
for(p=ht[i];p!=nullptr;p=p->next)
cout<data<<” “;
cout< }
}
//在下面补充实现动态查找算法
int main()
{
LinkHash LS;
int k;
while(1)
{
cin>>k;
if(!k) break;
try{
LS.HashSearch(k);
// LS.Display();
}
catch(const char
ms)
{
cout< }
}
LS.Display();
return 0;
}

输入

输出

样例输入

47 7 29 11 16 92 22 8 3 29 0

样例输出

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:

提示

来源

提交

  1. import java.util.Scanner;
  2. class Node{
  3. int data;
  4. Node next;
  5. }
  6. class LinkHash{
  7. int MaxSize = 11;
  8. Node[] ht = new Node[MaxSize];
  9. public LinkHash() {
  10. for (int i = 0; i < MaxSize; i++)
  11. ht[i] = null; //NULL is empty
  12. }
  13. void Display() {
  14. for (int i = 0; i < MaxSize; i++) {
  15. System.out.print("Hash address:" + i + ",value:");
  16. for (Node p = ht[i]; p != null; p = p.next)
  17. System.out.print(p.data + " ");
  18. System.out.println();
  19. }
  20. }
  21. int HashFunc(int k){
  22. return k % 11; //hash函数,假设为除余法,余数为11
  23. }
  24. int HashSearch(int k){
  25. int j = HashFunc(k);
  26. Node p = ht[j];
  27. while(p!=null && p.data != k) {
  28. p = p.next;
  29. }
  30. if(p!=null && p.data == k) return 1;
  31. else {
  32. Node s = new Node();
  33. s.data = k;
  34. s.next = ht[j];
  35. ht[j] = s;
  36. }
  37. return 0;
  38. }
  39. }
  40. public class Main {
  41. public static void main(String[] args) {
  42. LinkHash linkHash = new LinkHash();
  43. Scanner scanner = new Scanner(System.in);
  44. while(true){
  45. int k = scanner.nextInt();
  46. if(k == 0)break;
  47. linkHash.HashSearch(k);
  48. }
  49. linkHash.Display();
  50. }
  51. }