十年網(wǎng)站開(kāi)發(fā)經(jīng)驗(yàn) + 多家企業(yè)客戶(hù) + 靠譜的建站團(tuán)隊(duì)
量身定制 + 運(yùn)營(yíng)維護(hù)+專(zhuān)業(yè)推廣+無(wú)憂(yōu)售后,網(wǎng)站問(wèn)題一站解決
開(kāi)鏈法(哈希桶)是解決哈希沖突的常用手法,結(jié)構(gòu)如下:
數(shù)據(jù)結(jié)構(gòu)的設(shè)計(jì)思路是這樣的,定義一個(gè)K—V的鏈?zhǔn)焦?jié)點(diǎn)(Node),以數(shù)組方式存儲(chǔ)節(jié)點(diǎn)指針
實(shí)現(xiàn)代碼如下:
#include#include"HashTable.h" size_t GetSize() { static size_t index = 0; const int _PrimeSize = 28; static const unsigned long _PrimeList[_PrimeSize] = { 53ul, 97ul, 193ul, 389ul, 769ul, 1543ul, 3079ul, 6151ul, 12289ul, 24593ul, 49157ul, 98317ul, 196613ul, 393241ul, 786433ul, 1572869ul, 3145739ul, 6291469ul, 12582917ul, 25165843ul, 50331653ul, 100663319ul, 201326611ul, 402653189ul, 805306457ul, 1610612741ul, 3221225473ul, 4294967291ul }; return _PrimeList[index++]; } template struct HashBucketNode { HashBucketNode(const K& key, const V& value) :_key(key) , _value(value) , _next(NULL) {} K _key; V _value; HashBucketNode* _next; }; template > class HashBucket { public: typedef HashBucketNode Node; HashBucket() :_size(0) { _tables.resize(0); } bool Push(const K& key, const V& value) { _CheckCapacity(); size_t index = HashFunc()(key) % _tables.size(); Node*cur = _tables[index]; while (cur) { if (cur->_key == key&&cur->_value == value) return false; cur = cur->_next; } Node*tmp = new Node(key, value); if (_tables[index]) { _tables[index]->_next = tmp->_next; } _tables[index] = tmp; ++_size; return true; } void Swap(HashBucket & h) { swap(_size, h._size); _tables.swap(h._tables); } Node* find(const K& key, const V& value) { size_t index = HashFunc()(key) % _tables.size(); Node*cur = _tables[index]; while (cur) { if (cur->_key == key&&cur->_value == value) return cur; cur = cur->_next; } return NULL; } bool Remove(const K& key) { size_t index = HashFunc()(key) % _tables.size(); if (_tables[index]) { if (_tables[index]->key == key) { Node*tmp = _tables[index]; _tables[index] = tmp->_next; delete tmp; return true; } else { Node*cur = _tables[index]; while (cur->_next) { if (cur->_next->_key == key) { Node*tmp = cur->_next; cur->_next = cur->_next->_next; delete tmp; return true; } cur = cur->_next; } } } return false; } protected: void _CheckCapacity() { if (_size >= _tables.size()) { HashBucket tmp; tmp._tables.resize(GetSize()); for (size_t i = 0; i < tmp._tables.size(); ++i) { Node*cur = tmp._tables[i]; while (cur) { tmp.Push(cur->_key, cur->_value); cur = cur->_next; } } Swap(tmp); } } protected: vector _tables; size_t _size; };
如有不足希望指正,有疑問(wèn)希望提出
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性?xún)r(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專(zhuān)為企業(yè)上云打造定制,能夠滿(mǎn)足用戶(hù)豐富、多元化的應(yīng)用場(chǎng)景需求。