|
今天学数据结构, 写了HASH, 学习中, 坚持;(1)
template<typename T, typename Key = unsigned int> class hash { strUCt node { Key _key; T _data; node *_next; node(const Key &key, const T &x) : _key(key), _data(x), _next(NULL) { } }; node **_head; unsigned int _mod; public: hash(unsigned int mod = 13) : _mod(mod) { assert(mod); _head = new node*[_mod]; memset(_head, 0, sizeof(node *) * _mod); } ~hash() { clear(); delete[] _head; } void clear() { for(int i = 0; i < _mod; i++) { for(node *p; _head[i]; ) { p = _head[i], _head[i] = _head[i]->_next; delete p; } _head[i] = NULL; } } void visit(void func(unsigned int, const Key &, const T &)) { for(int i = 0; i < _mod; i++) for(node *p = _head[i]; p; p = p->_next) func(i + 1, p->_key, p->_data); } void push(const Key &key, const T &x) { unsigned int i = (unsigned int)key % _mod; if(_head[i]) { for(node *p = _head[i]; p && p->_key != key; p = p->_next) { if(!p->_next) { p->_next = new node(key, x); break; } } } else _head[i] = new node(key, x);
|