-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhash.cpp
More file actions
110 lines (92 loc) · 1.85 KB
/
Copy pathhash.cpp
File metadata and controls
110 lines (92 loc) · 1.85 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
#include <iostream>
#define N 9
using namespace std;
struct Node{
int key;
struct Node* next;
};
Node* bucket[N];
// the hash function
int hash_func(int key){
return key % 9;
}
Node* chained_hash_insert(int key){
int h = hash_func(key);
Node* p = new Node;
p->key = key;
p->next = NULL;
if(bucket[h] == NULL){
bucket[h] = p;
}else{
// insert befor current head
p->next = bucket[h];
bucket[h] = p;
}
return p;
}
Node* chained_hash_search(int key){
int h = hash_func(key);
Node* p = bucket[h];
while(p != NULL){
if(p->key == key)
break;
else
p = p->next;
}
return p;
}
Node* chained_hash_delete(int key){
int h = hash_func(key);
Node *pre, *p;
pre = NULL; //pre of p
p = bucket[h];
if(p == NULL) // empty list
return NULL;
while(p != NULL){
if(p->key == key)
break;
else{
pre = p;
p = p->next;
}
}
if(p == NULL) // not found
return NULL;
if(pre == NULL){
bucket[h] = NULL;
return p;
}else{
pre->next = p->next;
return p;
}
}
void print_hash_table(){
int i;
for(i=0; i<N; i++){
cout << "No. " << i << " bucket: ";
if(bucket[i] == NULL){
cout << "NULL" << endl;
}else{
Node* p = bucket[i];
while(p != NULL){
cout << p->key << " ";
p = p->next;
}
cout << endl;
}
}
}
int main(){
int a[] = {5, 28, 19, 15, 20, 33, 12, 17, 10};
int n = 9;
int i;
// init the bucket
for(i=0; i<N; i++){
bucket[i] = NULL; // no head pointers
}
for(i=0; i<n; i++){
chained_hash_insert(a[i]);
}
print_hash_table();
return 1;
}