#include <iostream>
#include <list>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;
class HashTable {
private:
vector<list<int>> table;
int size;
// Hash function to compute the index for a given key
int hashFunction(int key) const {
return key % size;
}
public:
HashTable(int s) : size(s) {
table.resize(size);
}
// Insert a key into the hash table
void insert(int key) {
int index = hashFunction(key);
auto& cell = table[index];
// Check if the key already exists
if (find(cell.begin(), cell.end(), key) == cell.end()) {
cell.push_back(key);
}
}
// Delete a key from the hash table
void remove(int key) {
int index = hashFunction(key);
auto& cell = table[index];
auto it = find(cell.begin(), cell.end(), key);
if (it != cell.end()) {
cell.erase(it);
}
}
// Search for a key in the hash table
bool search(int key) const {
int index = hashFunction(key);
const auto& cell = table[index];
return find(cell.begin(), cell.end(), key) != cell.end();
}
// Display the hash table
void display() const {
for (int i = 0; i < size; ++i) {
cout << "Bucket " << i << ": ";
for (const int& key : table[i]) {
cout << key << " -> ";
}
cout << "nullptr" << endl;
}
}
};
int main() {
HashTable hashTable(10);
hashTable.insert(10);
hashTable.insert(20);
hashTable.insert(30);
hashTable.insert(40);
hashTable.insert(50);
cout << "Hash Table:" << endl;
hashTable.display();
cout << "\nSearching for 20: " << (hashTable.search(20) ? "Found" : "Not Found") << endl;
cout << "Searching for 25: " << (hashTable.search(25) ? "Found" : "Not Found") << endl;
hashTable.remove(20);
cout << "\nHash Table after removing 20:" << endl;
hashTable.display();
return 0;
}