Last active
August 3, 2017 09:58
-
-
Save sukeesh/2763b3f7ad200d4e64a332c7f1f31747 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
const int TABLE_SIZE = 128; | |
class HashEntry | |
{ | |
public: | |
int key; | |
int val; | |
HashEntry(int key, int val) | |
{ | |
this->key = key; | |
this->val = val; | |
} | |
}; | |
class HashMap | |
{ | |
private: | |
HashEntry **table; | |
public: | |
HashMap() | |
{ | |
table = new HashEntry * [TABLE_SIZE]; | |
for ( int i = 0 ; i < TABLE_SIZE ; i ++ ){ | |
table[i] = NULL; | |
} | |
} | |
int HashFunc(int key){ | |
return key % TABLE_SIZE; | |
} | |
void insert(int key, int val){ | |
int hash = HashFunc(key); | |
while ( table[hash] != NULL && table[hash]->key != key ){ | |
hash = HashFunc(hash + 1); | |
} | |
if ( table[hash] != NULL ){ | |
delete table[hash]; | |
} | |
table[hash] = new HashEntry(key, val); | |
} | |
int Search(int key){ | |
int hash = HashFunc(key); | |
while( table[hash] != NULL && table[hash]->key != key ){ | |
hash = HashFunc(hash + 1); | |
} | |
if ( table[hash] == NULL ){ | |
return -1; | |
} | |
return table[hash]->val; | |
} | |
void Remove(int key){ | |
int hash = HashFunc(key); | |
while ( table[hash] != NULL ){ | |
if ( table[hash]->key == key ){ | |
break; | |
} | |
hash = HashFunc(hash + 1); | |
} | |
if ( table[hash] == NULL ){ | |
cout << "No element found at the key " << key << endl; | |
return; | |
} | |
delete table[hash]; | |
cout << "Element deleted" << endl; | |
} | |
~HashMap() | |
{ | |
for (int i = 0 ; i < TABLE_SIZE ; i ++ ){ | |
if ( table[i] != NULL ){ | |
delete table[i]; | |
} | |
} | |
delete[] table; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment