2014-04-24 00:05
题目:用拉链法设计一个哈希表。
解法:一个简单的哈希表,就看成一个数组就好了,每个元素是一个桶,用来放入元素。当有多个元素落入同一个桶的时候,就用链表把它们连起来。由元素值到哈希值的映射就是哈希函数了。
代码:
1 // 8.10 Design a hash table. Handle conflicts with chaining(linked lists). 2 #include <iostream> 3 #include <string> 4 #include <vector> 5 using namespace std; 6 7 class HashMap { 8 public: 9 HashMap() { 10 _buckets.resize(_bucket_num); 11 int i; 12 13 for (i = 0; i < _bucket_num; ++i) { 14 _buckets[i] = nullptr; 15 } 16 }; 17 18 bool contains(int key) { 19 key = (key > 0) ? key : -key; 20 key = key % _bucket_num; 21 LinkedList *ptr = _buckets[key]; 22 23 while (ptr != nullptr) { 24 if (ptr->key == key) { 25 return true; 26 } 27 } 28 29 return false; 30 }; 31 32 int& operator [] (int key) { 33 key = (key > 0) ? key : -key; 34 key = key % _bucket_num; 35 LinkedList *ptr = _buckets[key]; 36 37 if (ptr == nullptr) { 38 _buckets[key] = new LinkedList(key); 39 return _buckets[key]->val; 40 } 41 42 LinkedList *ptr2 = ptr->next; 43 if (ptr->key == key) { 44 return ptr->val; 45 } 46 47 while (ptr2 != nullptr) { 48 if (ptr2->key == key) { 49 return ptr2->val; 50 } else { 51 ptr = ptr->next; 52 ptr2 = ptr2->next; 53 } 54 } 55 ptr->next = new LinkedList(key); 56 ptr = ptr->next; 57 return ptr->val; 58 } 59 60 void erase(int key) { 61 key = (key > 0) ? key : -key; 62 key = key % _bucket_num; 63 LinkedList *ptr = _buckets[key]; 64 65 if (ptr == nullptr) { 66 return; 67 } else if (ptr->next == nullptr) { 68 if (ptr->key == key) { 69 delete _buckets[key]; 70 _buckets[key] = nullptr; 71 } 72 return; 73 } 74 75 if (ptr->key == key) { 76 _buckets[key] = ptr->next; 77 delete ptr; 78 return; 79 } 80 81 LinkedList *ptr2; 82 ptr2 = ptr->next; 83 84 while (ptr2 != nullptr) { 85 if (ptr2->key == key) { 86 ptr->next = ptr2->next; 87 delete ptr2; 88 return; 89 } else { 90 ptr = ptr->next; 91 ptr2 = ptr2->next; 92 } 93 } 94 } 95 96 ~HashMap() { 97 int i; 98 LinkedList *ptr; 99 100 for (i = 0; i < _bucket_num; ++i) { 101 ptr = _buckets[i]; 102 while (ptr != nullptr) { 103 ptr = ptr->next; 104 delete _buckets[i]; 105 _buckets[i] = ptr; 106 } 107 } 108 _buckets.clear(); 109 } 110 private: 111 struct LinkedList { 112 int key; 113 int val; 114 LinkedList *next; 115 LinkedList(int _key = 0, int _val = 0): key(_key), val(_val), next(nullptr) {}; 116 }; 117 118 static const int _bucket_num = 10000; 119 vector<LinkedList *> _buckets; 120 }; 121 122 int main() 123 { 124 HashMap hm; 125 string cmd; 126 int op1, op2; 127 128 while (cin >> cmd) { 129 if (cmd == "set") { 130 cin >> op1 >> op2; 131 hm[op1] = op2; 132 } else if (cmd == "get") { 133 cin >> op1; 134 cout << hm[op1] << endl; 135 } else if (cmd == "find") { 136 cin >> op1; 137 cout << (hm.contains(op1) ? "true" : "false") << endl; 138 } 139 } 140 141 return 0; 142 }