forked from DLily0129/Data-Structure
-
Notifications
You must be signed in to change notification settings - Fork 0
/
OpenHash.cpp
114 lines (99 loc) · 1.63 KB
/
OpenHash.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include <iostream>
using namespace std;
#define DEFAULT_DIVISOR 11
//链地址法结点定义
struct HashNode
{
int key;
HashNode *next;
HashNode();
HashNode(int _key,HashNode *_next=NULL);
};
HashNode::HashNode()
{
next=NULL;
}
HashNode::HashNode(int _key,HashNode *_next)
{
key=_key;
next=_next;
}
//链地址法散列表类定义
class OpenHashTable
{
public:
OpenHashTable(int divisor=DEFAULT_DIVISOR);
~OpenHashTable();
HashNode * Find(int key);
void Insert(int key);
void Display();
private:
HashNode *ht;
int div; //除留余数法的除数
int H(int key);
};
int OpenHashTable::H(int key)
{
return key%div;
}
OpenHashTable::OpenHashTable(int divisor)
{
div=divisor;
ht=new HashNode[divisor];
}
OpenHashTable::~OpenHashTable()
{
for(int i=0;i<div;i++)
{
HashNode *p=ht[i].next;
while(p!=NULL)
{
ht[i].next=p->next;
delete p;
p=ht[i].next;
}
}
delete[] ht;
}
HashNode * OpenHashTable::Find(int key)
{
int i=H(key);
HashNode *p=ht[i].next;
while(p!=NULL && p->key!=key)
p=p->next;
return p;
}
void OpenHashTable::Insert(int key)
{
int i=H(key);
HashNode *p=Find(key);
if(p==NULL) //关键字未找到,可以插入
ht[i].next=new HashNode(key,ht[i].next); //在表头插入
else
cout<<"该键值已存在"<<endl;
}
void OpenHashTable::Display()
{
for(int i=0;i<div;i++)
{
cout<<i<<": ";
HashNode *p=ht[i].next;
while(p!=NULL)
{
cout<<p->key<<" ";
p=p->next;
}
cout<<endl;
}
}
int main()
{
int a[]={32,40,36,53,16,46,71,27,42,24,49,64},i;
OpenHashTable htable(13);
for(i=0;i<12;i++)
htable.Insert(a[i]);
htable.Display();
if(htable.Find(27)!=NULL)
cout<<"查找27成功!"<<endl;
return 0;
}