-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhash_exe.cpp
104 lines (93 loc) · 1.78 KB
/
hash_exe.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
#include "hash_exe.h"
//#include <cmath>
#include <cassert>
#include <memory.h>
#include <stdlib.h>
Node ::Node( int key, const string &str ):key( key ), value( str ),next( 0 )
{
}
HashTable::HashTable()
{
memset( nodes, 0, sizeof(Node*) * SIZE );
}
unsigned int HashTable::hasher( int key )
{
// 最简单的hash函数
return abs(key) % SIZE;
}
bool HashTable::Insert( int key, const std::string &value )
{
uint32_t_ adr = hasher( key );
Node * node = nodes[adr];
if(node == 0)
{
nodes[adr] = new Node( key, value );
}
else
{
return Insert( &node->next, key, value );
}
}
bool HashTable::Insert( Node** next, int key, const string& value )
{
Node *node = *next;
if( node == 0 )
{
(*next) = new Node( key, value );
return true;
}
else
{
return Insert( &node->next, key, value );
}
}
bool HashTable::Find( int key )
{
uint32_t_ adr = hasher( key );
Node *node = nodes[adr];
if( node == 0 )
{
return false;
}
else
{
do
{
if( node->key == key )
{
return true;
}
else
{
node = node->next;
}
}while( node != 0 );
return false;
}
}
Node* HashTable::FindNode( int key )
{
uint32_t_ adr = hasher( key );
Node *node = nodes[adr];
if(node != 0)
{
do
{
if( node->key == key )
{
return node;
}
else
{
node = node->next;
}
}while( node != 0);
}
return 0;
}
string & HashTable::operator[](int key )
{
Node* node = FindNode( key );
assert( node != 0 );
return node->value;
}