Pagini recente » Cod sursa (job #1467297) | Cod sursa (job #1421868) | Cod sursa (job #2520878) | Cod sursa (job #1421481) | Cod sursa (job #712022)
Cod sursa(job #712022)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int N, n, c;
typedef struct node_t {
int x;
struct node_t *next;
} node;
node *hashtable[666013];
int hash(int x) {
return x % 666013;
}
void hash_insert(int x) {
int xhash = hash(x);
int add = 1;
if (hashtable[xhash] == NULL) {
hashtable[xhash] = (node *)malloc(sizeof(node));
hashtable[xhash]->x = x;
hashtable[xhash]->next = NULL;
}
else {
node *aux = hashtable[xhash];
node *tmp = (node *)malloc(sizeof(node));
tmp->x = x;
tmp->next = NULL;
while (aux->next) {
if (aux->x == x) {
add = 0;
break;
}
aux = aux->next;
}
if (add)
aux->next = tmp;
}
}
void hash_delete(int x) {
int xhash = hash(x);
node *tmp = hashtable[xhash];
if (tmp) {
if (tmp->x == x) {
hashtable[xhash] = tmp->next;
}
else {
node *prev = tmp;
tmp = tmp->next;
if (tmp) {
while (tmp->next) {
if (tmp->x == x) {
prev->next = NULL;
}
prev = prev->next;
tmp = tmp->next;
}
}
else {
if (prev->x == x) {
hashtable[xhash] = NULL;
}
}
}
}
}
int hash_exists(int x) {
int xhash = hash(x);
int result = 0;
node *tmp = hashtable[xhash];
if (tmp) {
while(tmp) {
if (tmp->x == x) {
result = 1;
break;
}
tmp = tmp->next;
}
}
return result;
}
int main(int argc, char **argv) {
freopen("hashuri.in", "r", stdin);
freopen("hashuri.out", "w", stdout);
memset(hashtable, 0, sizeof(hashtable));;
scanf("%d", &N);
int i;
for (i = 0; i < N; i++) {
scanf("%d %d", &c, &n);
if (c == 1) {
hash_insert(n);
}
else if (c == 2) {
hash_delete(n);
}
else {
printf("%d\n", hash_exists(n));
}
}
return 0;
}