Cod sursa(job #472452)

Utilizator robigiirimias robert robigi Data 24 iulie 2010 21:44:57
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.56 kb


//#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>

#define NMAX 1000000

typedef struct node {
	int key;
	struct node *next;
} Node;

Node *Hash[NMAX];

inline int hashFunction(int i) {
	return i % NMAX;
}

void insert(int val) {
	int pos = hashFunction(val);

	Node *newNode = (Node*)calloc(1, sizeof(Node));
	newNode->key = val;
	newNode->next = Hash[pos];
	Hash[pos] = newNode;

}

int find(int val) {
	int pos = hashFunction(val);
	
	Node *curr; 
	for (curr = Hash[pos]; curr != NULL; curr = curr->next)
		if (curr->key == val)
			return 1;
	return 0;
}

void deletee(int val) {
	int pos = hashFunction(val);
	
	if (Hash[pos] == NULL)
		return;

	Node *helper;
	if (Hash[pos]->key == val) {
		helper = Hash[pos]->next;
		free(Hash[pos]);
		Hash[pos] = helper;
		return;
	}

	Node *curr;
	for (curr = Hash[pos]; curr->next != NULL; curr = curr->next)
		if (curr->next->key == val) {
			helper = curr->next->next;
			free(curr->next);
			curr->next = helper;
			return;
		}
}


int main() {
	freopen("hashuri.in", "r", stdin);
	freopen("hashuri.out", "w", stdout);

	int t, op, val;
	for (scanf("%d", &t); t > 0; -- t) {
		scanf("%d%d", &op, &val);
		switch(op) {
			case 1:
				insert(val);
				break;
			case 2:
				deletee(val);
				break;
			case 3:
				printf("%d\n", find(val));
				break;
		}
	}
	
	int i;
	Node *curr, *helper;
	for (i = 0; i < NMAX; ++ i) {
		for (curr = Hash[i]; curr != NULL; curr = helper) {
			helper = curr->next;
			free(curr);;
		}
	}

	return 0;
}