CODE:
#include <iostream>
#include <list>
#include <vector>
using namespace std;
class HashTable {
private:
int size;
vector<list<int>> table;
public:
HashTable(int s) : size(s) {
table.resize(size);
}
// Hash function to map values to keys
int hash(int key) {
return key % size;
}
// Function to insert key into hash table
void insert(int key) {
int index = hash(key);
table[index].push_back(key);
}
// Function to search for a key in the hash table
bool search(int key) {
int index = hash(key);
for (auto it = table[index].begin(); it != table[index].end(); ++it) {
if (*it == key)
return true;
}
return false;
}
// Function to display the hash table
void display() {
for (int i = 0; i < size; ++i) {
cout << "[" << i << "]";
for (auto it = table[i].begin(); it != table[i].end(); ++it) {
cout << " --> " << *it;
}
cout << endl;
}
}
};
int main() {
HashTable ht(10); // Hash table of size 10
// Insert some keys
ht.insert(5);
ht.insert(15);
ht.insert(25);
ht.insert(35);
ht.insert(45);
// Display the hash table
ht.display();
// Search for a key
int searchKey = 15;
if (ht.search(searchKey))
cout << "Key " << searchKey << " found in the hash table." << endl;
else
cout << "Key " << searchKey << " not found in the hash table." << endl;
return 0;
}