#include <iostream>
using namespace std;
template<typename Value_type>
struct tagEntry{
string _key;
Value_type _value;
struct tagEntry<Value_type>* _pNext;
tagEntry(string k, Value_type v):_key(k), _value(v), _pNext(NULL){}
};
template<typename Value_type>
class Hashtable {
typedef struct tagEntry<Value_type> Entry;
public:
Hashtable(){
_capacity = 31;
_size = 0;
_ptable = new *Entry[_capacity];
}
~Hashtable(){
_size = 0;
for (int i = 0; i < _capacity; i++) {
Entry* cur = _ptable[i];
while(cur) {
Entry* tmp = cur;
cur = cur->_pNext;
delete cur;
}
}
_capacity = 0;
delete[] _ptable;
}
size_t size() {return _size;}
void insert(string& key, Value_type& value) {
_Expand();
size_t index = hasher(key) % _capacity;
Entry* pEntry = _ptable[index];
if (!pEntry)
pEntry = new Entry(key, value);
else {
while (pEntry->_pNext)
pEntry = pEntry->_pNext;
pEntry->_pNext = new Entry(key, value);
}
_size++;
return;
}
Value_Type& find(const string& key) {
size_t = index hasher(key) & _capacity;
Entry* pEntry = _ptable[index];
while (pEntry) {
if (pEntry->_key != key)
pEntry = pEntry->_pNext;
else
return pEntry->_value;
}
return;
}
private:
Entry** _ptable;
size_t _capacity;
size_t _size;
void insert(Entry* node) {
size_t index = haser(cur->key) & _capacity;
Entry* pEntry = _ptable[index];
if (!pEntry)
pEntry = node;
else {
while (pEntry->_pNext)
pEntry = pEntry->_pNext;
pEntry->_pNext = node;
}
}
void _Expand() {
if (_size < _capacity)
return;
size_t new_capacity = _capacity * 2;
Entry* pold_table = _ptable;
_ptable = new *Entry[_capacity];
for (int i = 0; i < _capacity; i++) {
Entry *cur = pold_table[i];
while(cur) {
insert(cur);
cur = cur->_pNext;
}
return;
}
size_t hasher(string& s) {
register size_t h = 0;
for(string::iterator iter = s.begin(); iter != s.end(); iter++)
h = h*31 + *iter;
return h;
}
};
int main() {
// your code goes here
Hashtable<int> table;
table.insert("abc",1);
table.insert("bcd",2);
cout<<table.find("abc")<<" "<<table.find("bcd")<<endl;
}
hashtable实现(未编译)
最新推荐文章于 2024-08-02 16:32:59 发布