Pagini recente » Cod sursa (job #2285726) | Cod sursa (job #270797) | Cod sursa (job #1004434) | Cod sursa (job #2399329) | Cod sursa (job #2288254)
#include <iostream>
#include <fstream>
std::ifstream f("hashuri.in");
std::ofstream g("hashuri.out");
class HashMap {
private:
struct HashNode {
int value;
HashNode*next;
};
HashNode **table;
int capacity;
int getHashKey(int value) {
return value % capacity;
}
public:
HashMap(int capacity) {
this->capacity = capacity;
table = new HashNode*[capacity];
for (int i = 0; i < capacity; ++i)
table[i] = NULL;
}
void insert(int value) {
int key = this->getHashKey(value);
HashNode*t = new HashNode;
t->value = value;
t->next = NULL;
if (table[key] == NULL) {
table[key] = t;
return;
}
HashNode*q;
for (q = table[key]; q->next; q = q->next)
if (q->value == value)
return;
if (q->value == value)
return;
q->next = t;
}
bool search(int value) {
int key = this->getHashKey(value);
if (table[key] == NULL)
return false;
for (HashNode*q = table[key]; q; q = q->next)
if (q->value == value)
return true;
return false;
}
void remove(int value) {
int key = this->getHashKey(value);
if (table[key] == NULL)
return;
if (table[key]->value == value) {
HashNode*temp = table[key];
table[key] = table[key]->next;
delete temp;
return;
}
HashNode*q;
for (q = table[key]; q->next; q = q->next)
if (q->next->value == value) {
HashNode*temp = q->next;
q = q->next->next;
delete temp;
return;
}
}
void displayTable() {
std::cout << "\n[Hash Table]\n";
for (int i = 0; i < capacity; ++i) {
std::cout << "Key: " << i << " <-> nodes: ";
for (HashNode*it = table[i]; it != NULL; it = it->next)
std::cout << it->value << " ";
std::cout << "\n";
}
std::cout << "\n";
}
};
int main() {
int n;
f >> n;
HashMap* h = new HashMap(499999);
int op, x;
for (int i = 1; i <= n; ++i) {
f >> op >> x;
if (op == 1) {
h->insert(x);
continue;
}
if (op == 2) {
h->remove(x);
continue;
}
g << h->search(x) << '\n';
}
return 0;
}