Cod sursa(job #1651547)

Utilizator Mihai22eMihai Ionut Enache Mihai22e Data 13 martie 2016 15:27:39
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.89 kb
#include <cstdio>
using namespace std;

class Node {
	public:
		int value;
		Node *next;
		
		Node() {
			value = -1;
			next = NULL;
		}

		Node(int value) {
			this->value = value;
			next = NULL;
		}
};

class HashTable {
	private:
		const int MOD = 666013;
		Node **hashTable = new Node* [MOD];
		
		int hash(int value) {
			return value % MOD;
		}

	public:
		void insertValue(int value) {
			int list = hash(value);
			
			if(hashTable[list] == NULL) {
				hashTable[list] = new Node(value);
			}
			else {
				Node *node = hashTable[list];
				
				while(node->next != NULL) {
					if(node->value == value) {
						return;
					}
					node = node->next;
				}

				Node *newNode = new Node(value);
				node->next = newNode;
			}
		}

		void deleteValue(int value) {
			int list = hash(value);

			if(hashTable[list] == NULL) {
				return;
			}
			else {
				if(hashTable[list]->value == value) {
					Node *tmp = hashTable[list];
					hashTable[list] = tmp->next;
					delete tmp;
				}
				else {
					Node *node = hashTable[list];
					
					while(node->next != NULL && node->next->value != value) {
						node = node->next;
					}

					if(node->next != NULL) {
						Node *tmp = node->next;
						node->next = node->next->next;
						delete tmp;
					}
				}
			}
		}

		bool searchValue(int value) {
			int list = hash(value);
			
			Node *node = hashTable[list];
			
			while(node != NULL && node->value != value) {
				node = node->next;
			}

			if(node != NULL) {
				return true;
			}
			else {
				return false;
			}
		}
};

int main() {
	freopen("hashuri.in", "r", stdin);
	freopen("hashuri.out", "w", stdout);
	
	int n;
	scanf("%d", &n);
	
	HashTable h;
	for(int i = 0; i < n; ++i) {
		int op, x;
		scanf("%d %d", &op, &x);
		
		if(op == 1) {
			h.insertValue(x);
		}
		else if(op == 2) {
			h.deleteValue(x);
		}
		else {
			printf("%d\n", h.searchValue(x));
		}
	}

	fclose(stdin);
	fclose(stdout);
	
	return 0;
}