C++泛型编程实现哈希表(开散列法)
生活随笔
收集整理的這篇文章主要介紹了
C++泛型编程实现哈希表(开散列法)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
代碼如下:
#include <iostream> #include <vector> using namespace std;template<typename K> struct HashNode {typedef HashNode<K> Node;K _val;Node * _next;HashNode(const K & val):_val(val),_next(nullptr){} };template<typename K> class HashTable { public:typedef HashNode<K> Node;HashTable(int n = 10):_ht(10),_size(0){}bool insert(const K & val){checkCapacity();int idx = val % _ht.size();Node *cur = _ht[idx];while (cur){if (cur->_val == val) return false;cur = cur->_next;}cur = new Node(val);cur->_next = _ht[idx];_ht[idx] = cur;++_size;return true;}void checkCapacity(){if (_size == _ht.size()){int newC = _size == 0 ? 10 : 2 * _size;vector<Node *> newHt(newC);for (size_t i = 0; i < _ht.size(); i++){Node *cur = _ht[i];while (cur){Node *next = cur->_next;int idx = cur->_val % newHt.size();cur->_next = newHt[idx];newHt[idx] = cur;cur = next;}_ht[i] = nullptr;}swap(_ht, newHt);}}Node *find(const K & val){int idx = val % _ht.size();Node *cur = _ht[idx];while (cur){if (cur->_val == val) return cur;cur = cur->_next;}return nullptr;}bool erase(const K & val){Node *node = find(val);if (node){int idx = val % _ht.size();Node *cur = _ht[idx];Node *prev = nullptr;while (cur != node){prev = cur;cur = cur->_next;}Node *next = cur->_next;if (prev) prev->_next = next;else _ht[idx] = next;--_size;delete node;return true;}return false;}private:vector<Node *> _ht;int _size; };int main() {HashTable<int> h;h.insert(12321);h.insert(131);h.insert(123);cout << h.find(131)->_val << endl;return 0; }測試結果:
總結
以上是生活随笔為你收集整理的C++泛型编程实现哈希表(开散列法)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++泛型编程实现哈希表(闭散列---线
- 下一篇: 投影仪“自动选择投影区”,联想在智博会展