diff --git a/hash_table1.cpp b/hash_table1.cpp new file mode 100644 index 0000000..498de6b --- /dev/null +++ b/hash_table1.cpp @@ -0,0 +1,332 @@ +#adding different functions to use hash tables + /* + + *C++ Program to Implement Hash Tables + + */ + + #include + + #include + + #include + + #include + + using namespace std; + + const int TABLE_SIZE = 128; + + + + /* + + * HashEntry Class Declaration + + */ + + class HashEntry + + { + + public: + + int key; + + int value; + + HashEntry(int key, int value) + + { + + this->key = key; + + this->value = value; + + } + + }; + + + + /* + + * HashMap Class Declaration + + */ + + class HashMap + + { + + private: + + HashEntry **table; + + public: + + HashMap() + + { + + table = new HashEntry * [TABLE_SIZE]; + + for (int i = 0; i< TABLE_SIZE; i++) + + { + + table[i] = NULL; + + } + + } + + /* + + * Hash Function + + */ + + int HashFunc(int key) + + { + + return key % TABLE_SIZE; + + } + + /* + + * Insert Element at a key + + */ + + void Insert(int key, int value) + + { + + 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, value); + + } + + /* + + * Search Element at a key + + */ + + 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; + + else + + return table[hash]->value; + + } + + + + /* + + * Remove Element at a key + + */ + + 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 key "<>choice; + + switch(choice) + + { + + case 1: + + cout<<"Enter element to be inserted: "; + + cin>>value; + + cout<<"Enter key at which element to be inserted: "; + + cin>>key; + + hash.Insert(key, value); + + break; + + case 2: + + cout<<"Enter key of the element to be searched: "; + + cin>>key; + + if (hash.Search(key) == -1) + + { + + cout<<"No element found at key "<>key; + + hash.Remove(key); + + break; + + case 4: + + exit(1); + + default: + + cout<<"\nEnter correct option\n"; + + } + + } + + return 0; + + }