Pagini recente » Cod sursa (job #1957891) | Cod sursa (job #586461) | Cod sursa (job #305213) | Cod sursa (job #458958) | Cod sursa (job #2591360)
#include <stdlib.h>
#include <stdio.h>
#define MOD 666013
typedef struct cell {
int value;
struct cell *next;
} t_cell;
typedef struct list {
t_cell *start, *end;
} t_list;
typedef t_list* t_hash;
typedef int (* f_hash) (int);
t_list *create_list();
void free_list(t_list *list);
int push_back_list(t_list **list, int value);
int remove_list(t_list *list, int value);
int check_list(t_list *list, int value);
int add_hash(t_hash *hash, f_hash f, int value);
int remove_hash(t_hash *hash, f_hash f, int value);
int check_hash(t_hash *hash, f_hash f, int value);
t_list *create_list()
{
t_list *list;
list = (t_list *) malloc(sizeof(t_list));
if(list == NULL) {
return NULL;
}
list->start = list->end = NULL;
return list;
}
void free_list(t_list *list)
{
if(list == NULL) {
return;
}
for(t_cell *cell = list->start, *next = NULL; cell != NULL; cell = next) {
next = cell->next;
free(cell);
}
}
int push_back_list(t_list **list, int value)
{
t_cell *cell;
if(*list == NULL) {
*list = create_list();
if(*list == NULL) {
return -1;
}
}
cell = (t_cell *) malloc(sizeof(t_cell));
if(cell == NULL) {
return -1;
}
cell->value = value;
cell->next = NULL;
if((*list)->end == NULL) {
(*list)->start = (*list)->end = cell;
}
else {
(*list)->end->next = cell;
(*list)->end = cell;
}
return 0;
}
int remove_list(t_list *list, int value) {
if(list == NULL) {
return -1;
}
for(t_cell *cell = list->start, *last = NULL; cell != NULL;) {
if(cell->value == value) {
if(last == NULL) {
list->start = cell->next;
}
else {
last->next = cell->next;
}
if(list->end == cell) {
list->end = last;
}
free(cell);
return 0;
}
else {
last = cell;
cell = cell->next;
}
}
return -1;
}
int check_list(t_list *list, int value) {
if(list == NULL) {
return 0;
}
for(t_cell *cell = list->start; cell != NULL; cell = cell->next) {
if(cell->value == value) {
return 1;
}
}
return 0;
}
int add_hash(t_hash *hash, f_hash f, int value)
{
int p;
p = f(value);
if(check_list(hash[p], value) == 0) {
return push_back_list(&(hash[p]), value);
}
return -1;
}
int remove_hash(t_hash *hash, f_hash f, int value)
{
int p;
p = f(value);
return remove_list(hash[p], value);
}
int check_hash(t_hash *hash, f_hash f, int value)
{
int p;
p = f(value);
return check_list(hash[p], value);
}
int modulo(int value)
{
return value % MOD;
}
t_hash hash[MOD];
int main()
{
FILE *input_file = fopen("hashuri.in", "r"),
*output_file = fopen("hashuri.out", "w");
int n, op, val;
fscanf(input_file, "%d", &n);
for(; n; n--) {
fscanf(input_file, "%d %d", &op, &val);
switch(op) {
case 1:
add_hash(hash, &modulo, val);
break;
case 2:
remove_hash(hash, &modulo, val);
break;
case 3:
fprintf(output_file, "%d\n", check_hash(hash, &modulo, val));
break;
}
}
fclose(input_file);
fclose(output_file);
}