Cod sursa(job #1540673)

Utilizator diana97Diana Ghinea diana97 Data 3 decembrie 2015 00:07:51
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.56 kb
#include <iostream>
#include <fstream>

using namespace std;

ifstream f ("hashuri.in");
ofstream g ("hashuri.out");

const int MOD = 666013;


struct hashElement{
    int key;
    int value;
    hashElement *next;
    hashElement *prev;

    hashElement(int key) {
        this->key = key;
        this->value = 1;
        this->next = this->prev = NULL;
    };
};


class hashTable {
    private:
        hashElement *table[MOD];
    public:
        hashTable() {
            for (int i = 0; i < MOD; i++) table[i] = NULL;
        };

        int get_hash(int key) {
            if (key < 0) key = (-1) * key;
            return key % MOD;
        };

        void insert_element(int key) {
            int line_index = get_hash(key);

            hashElement *crt = table[line_index];
            hashElement *prev = NULL;

            while(crt != NULL) {
                if (crt->key == key) return;
                prev = crt;
                crt = crt->next;
            }

            //crt e NULL
            crt = new hashElement(key);
            crt->prev = prev;
            if (prev != NULL) prev->next = crt;

            if (table[line_index] == NULL) table[line_index] = crt;
        }

        bool find_element(int key) {
            int line_index = get_hash(key);

            hashElement *crt = table[line_index];
            hashElement *prev = NULL;

            while(crt != NULL) {
                if (crt->key == key) return true;
                prev = crt;
                crt = crt->next;
            }

            return false;
        }

        void delete_element(int key) {
            int line_index = get_hash(key);

            hashElement *crt = table[line_index];
            hashElement *prev = NULL;
            hashElement *next = NULL;

            while(crt != NULL) {
                if (crt->key == key) {
                    next = crt->next;
                    if (next != NULL) next->prev = prev;
                    if (prev != NULL) prev->next = next;
                    else {
                        table[line_index] = next;
                    }
                    delete(crt);
                    return;
                }
                prev = crt;
                crt = crt->next;
            }
        };
};


int main() {
    int n, op, key;

    hashTable *hash_table = new hashTable();

    f >> n;

    for (int i = 1; i <= n; i++) {
        f >> op >> key;
        if (op == 1) hash_table->insert_element(key);
        else if (op == 2) hash_table->delete_element(key);
        else g << hash_table->find_element(key) << '\n';
    }

    return 0;
}