今天学数据结构, 写了HASH, 学习中, 坚持;

王朝other·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

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);

}

T * find(const Key &key)

{

unsigned int i = (unsigned int)key % _mod;

for(node *p = _head[i]; p; p = p->_next)

{

if(p->_key == key)

return &p->_data;

}

return NULL;

}

void pop(const Key &key)

{

unsigned int i = (unsigned int)key % _mod;

node *t = NULL, *pre = NULL;

if(_head[i])

{

if(_head[i]->_key == key)

t = _head[i], _head[i] = _head[i]->_next;

else

{

for(pre = _head[i], t = pre->_next; t; t = t->_next)

{

if(t->_key == key)

{

pre->_next = t->_next;

break;

}

}

}

}

if(t)

delete t;

}

void pop(const Key &key, T &data)

{

unsigned int i = (unsigned int)key % _mod;

node *t = NULL, *pre = NULL;

if(_head[i])

{

if(_head[i]->_key == key)

t = _head[i], _head[i] = _head[i]->_next;

else

{

for(pre = _head[i], t = pre->_next; t; t = t->_next)

{

if(t->_key == key)

{

pre->_next = t->_next;

break;

}

}

}

}

if(t)

{

data = t->_data;

delete t;

}

}

};

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航