-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhash.cpp
More file actions
203 lines (170 loc) · 3.08 KB
/
hash.cpp
File metadata and controls
203 lines (170 loc) · 3.08 KB
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
#include <iostream>
using namespace std;
#define max_size 7
class Node
{
public:
Node *link;
int key;
Node(int data){ key = data; link = NULL;}
friend class Hash;
};
class Hash
{
private:
Node *head;
public:
void insertKey(int key);
void deleteKey(int key);
void finding(int key);
Hash(){head=NULL; }
int findKey(int key);
int hashKey(int key){return key%max_size;}
Node* getHead(){return head;}
void traverse();
};
Hash myHash[max_size];
int Hash::findKey(int key)
{
Node *p;
p=head;
while(p!=NULL&&p->key!=key)
{
p=p->link;
}
if(!p)
{
return 0;
}
else
{
return 1;
}
}
void Hash::finding(int key)
{
Node *p;
p=head;
while(p!=NULL&&p->key!=key)
{
p=p->link;
}
if(!p)
{
cout << "No data!!!" << endl;
}
else
{
cout << key << "를 찾았습니다." << endl;
}
}
void Hash::insertKey(int key)
{
Node *temp = new Node(key);
Node *p;
if(head==NULL)
{
head = temp;
}
else
{
p=head;
while( p->link != NULL)
{
p = p->link;
}
p->link = temp;
}
}
void Hash::deleteKey(int key)
{
Node *p , *q;
p=head;
if(head->key==key)
{
q=p;
p=p->link;
head=p;
delete q;
}
else
{
while(p->key!=key&&p!=NULL)
{
q=p;
p=p->link;
}
if(p->key==key)
{
q->link = p->link;
delete p;
}
else
{
cout << "없는 데이터입니다" << endl;
}
}
}
void Hash::traverse()
{
Node *p;
p=head;
while(p!=NULL)
{
cout << p->key << " ";
p=p->link;
}
cout << endl;
}
int main()
{
int index;
int input;
int num;
Hash h;
while(1)
{
cout << "1.insert 2.delete 3.traverse 4.find 5.quit " << endl;
cin >> input;
if(input == 1)
{
cout << "입력할 데이터는? " << endl;
cin >> num;
index = h.hashKey(num);
if( !myHash[index].findKey(num))
myHash[index].insertKey(num);
else
cout << "이미 존재하는 데이터입니다." <<endl;
}
else if(input == 2)
{
cout << "삭제할 데이터는? " << endl;
cin >> num;
index = h.hashKey(num);
myHash[index].deleteKey(num);
}
else if(input == 3)
{
for(int i = 0 ; i < max_size ; i++)
{
cout << i << "번" << ":";
myHash[i].traverse();
}
}
else if(input == 4)
{
cout << "찾을 데이터는 ? " << endl;
cin >> num;
index = h.hashKey(num);
myHash[index].finding(num);
}
else if(input == 5)
{
break;
}
else
{
cout << "Bad Command!!!!!!" << endl;
}
}
}