Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

simple chaining hash table implementation

  • Loading branch information...
commit 96009ea60d6e9dae7c1f3be9c89337b093a67f81 1 parent 4be2f2c
Sukwon Oh authored
View
85 dataStructure/hashTable/hashTable.h
@@ -0,0 +1,85 @@
+#ifndef __HASHTABLE_H_
+#define __HASHTABLE_H_
+
+#include <exception>
+#include <string>
+
+template <typename K, typename V>
+class HashTable
+{
+public:
+ HashTable()
+ : ratio(0), numElements(0), size(10) {
+ table = new Item*[size];
+ for (int i=0; i<size; ++i) table[i] = NULL;
+ }
+ void insert(const K& key, const V& val) {
+ if (ratio > 0.7) rehash();
+ int h = hash(key, size);
+ Item* item = new Item;
+ item->key = key;
+ item->val = val;
+ item->next = table[h];
+ table[h] = item;
+ numElements++;
+ ratio = numElements/size;
+ }
+ V& operator[](const K& key) const {
+ int h = hash(key, size);
+ if (table[h]) {
+ Item* cur = table[h];
+ while (cur && cur->key != key) {
+ cur = cur->next;
+ }
+ if (cur == NULL) throw std::exception();
+ else return cur->val;
+ }
+ throw std::exception();
+ }
+private:
+ int ratio;
+ int numElements;
+ int size;
+ void rehash() {
+ int prevSize = size;
+ size *= 10;
+ Item** table2 = new Item*[size];
+ for (int i=0; i<size; ++i) table2[i] = NULL;
+ for (int i=0; i<prevSize; ++i) {
+ if (table[i]) {
+ int h = hash(table[i]->key, size);
+ table2[h] = table[i];
+ }
+ }
+ for (int i=0; i<prevSize; ++i) delete [] table[i];
+ delete [] table;
+ table = table2;
+ ratio = numElements / size;
+ }
+ struct Item {
+ ~Item() { delete next; }
+ Item* next;
+ K key;
+ V val;
+ };
+ Item** table;
+};
+
+template <typename K>
+int hash(const K& key, int size) {
+ throw std::exception();
+}
+
+int hash(const int& key, int size) {
+ return key % size;
+}
+
+int hash(const std::string& key, int size) {
+ int h = 0;
+ for (int i=0; i<key.size(); ++i) {
+ h = 101 * h + (int)key[i];
+ }
+ return h % size;
+}
+
+#endif
View
35 dataStructure/hashTable/test.cc
@@ -0,0 +1,35 @@
+#include "hashTable.h"
+#include <iostream>
+#include <string>
+using namespace std;
+
+int main()
+{
+ HashTable<string, int> h;
+ h.insert("hello", 1);
+ h.insert("hi", 2);
+ h.insert("how are you?", 3);
+ h.insert("i am fine.", 4);
+ h.insert("thank you." , 5);
+
+ cout << h["hello"] << endl;
+ cout << h["hi"] << endl;
+ cout << h["how are you?"] << endl;
+ cout << h["i am fine."] << endl;
+ cout << h["thank you."] << endl;
+
+ HashTable<int, int> h2;
+ h2.insert(1231341, 1);
+ h2.insert(242141, 2);
+ h2.insert(231, 3);
+ h2.insert(51251, 4);
+ h2.insert(124, 5);
+
+ cout << h2[1231341] << endl;
+ cout << h2[242141] << endl;
+ cout << h2[231] << endl;
+ cout << h2[51251] << endl;
+ cout << h2[124] << endl;
+
+ return 0;
+}
Please sign in to comment.
Something went wrong with that request. Please try again.