Cod sursa(job #1319632)

Utilizator alexandru.ghergutAlexandru-Gabriel Ghergut alexandru.ghergut Data 17 ianuarie 2015 11:35:23
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.76 kb
#include <fstream>

using namespace std;

#define hashSize 666013

struct Node
{
    int val;
    Node *next;
};

int hashFunction(int x);
void hashInsert(int x, Node *hashTable[]);
void hashDelete(int x, Node *hashTable[]);
bool hashSearch(int x, Node *hashTable[]);

int main()
{
    int i, N, op, x;
    Node *hashTable[hashSize];
    for (i = 0; i < hashSize; i++)
    {
        hashTable[i] = new Node;
        hashTable[i]->next = NULL;
    }

    ifstream f("hashuri.in");
    f >> N;
    ofstream g("hashuri.out");
    for (i = 1; i <= N; i++)
    {
        f >> op >> x;
        if (op == 1)
            hashInsert(x, hashTable);
        else if (op == 2)
            hashDelete(x, hashTable);
        else if (op == 3)
            g << hashSearch(x, hashTable) << "\n";
    }

    f.close();
    g.close();
    return 0;
}

int hashFunction(int x)
{
    return x % hashSize;
}

void hashInsert(int x, Node *hashTable[])
{
    int pos = hashFunction(x);
    Node *current = hashTable[pos];
    while (current->next)
    {
        current = current->next;
        if (current->val == x)
            return;
    }
    current->next = new Node;
    current->next->val = x;
    current->next->next = NULL;
}

void hashDelete(int x, Node *hashTable[])
{
    int pos = hashFunction(x);
    Node *current = hashTable[pos];
    while(current->next && current->next->val != x)
        current = current->next;

    if (current->next)
    {
        Node *tmp = current->next;
        current->next = current->next->next;
        delete tmp;
    }
}

bool hashSearch(int x, Node *hashTable[])
{
    int pos = hashFunction(x);
    Node *current = hashTable[pos]->next;
    while(current)
    {
        if (current->val == x)
            return true;
        current = current->next;
    }

    return false;
}