Cod sursa(job #674207)

Utilizator ukiandreaAndreea Lucau ukiandrea Data 5 februarie 2012 19:48:53
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.12 kb
#include <stdio.h>
#include <stdlib.h>

struct node {
	int value;
	struct node *next;
};

struct list {
	node *head;
};

list* create_list()
{
	list *l = (list*)calloc(1, sizeof(list));
	l->head = NULL;
	return l;
}

void insert_list(list* l, int value)
{
    node *n = (node*)calloc(1, sizeof(node));
    n->value = value;

    n->next = l->head;
    l->head = n;
}

void delete_value(list *l, int value)
{
    if (l->head == NULL)
        return;

    if (l->head->value == value) {
        node *n = l->head;
        l->head = n->next;
        n->next = NULL;
        free(n);
        return;
    }

    node *n = l->head;

    while (n->next && n->next->value != value) 
        n = n->next;
    
    if (n->next && n->next->value == value) {
        node *x = n->next;
        n->next = x->next;
        x->next = NULL;
        free(x);
    }
}

int find_value(list *l, int value)
{
    if (l->head == NULL)
        return 0;

    node *n = l->head;
    while (n) {
        if (n->value == value)
            return 1;
        n = n->next;
    }

    return 0;
}

void destroy_list(list **l)
{
	while ((*l)->head != NULL) {
		node *p = (*l)->head;
		(*l)->head = (*l)->head->next;
		
		free(p);
	}
}

#define HASH_SIZE   200000
list* table[HASH_SIZE];

void add_hash_value(int v)
{
    int t = v % HASH_SIZE;
    insert_list(table[t], v);
}

void delete_hash_value(int v)
{
    int t = v % HASH_SIZE;
    delete_value(table[t], v);
}

int find_hash_value(int v)
{
    int t = v % HASH_SIZE;
    return find_value(table[t], v);
}

int main()    
{
    int n;

    for (int i = 0; i < HASH_SIZE; i++) 
        table[i] = create_list();

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

    scanf("%d\n", &n);

    for (int i = 0; i < n; i++) {
        int code, value;
        scanf("%d %d\n", &code, &value);
        switch (code) {
            case 1:
                add_hash_value(value);
                break;
            case 2:
                delete_hash_value(value);
                break;
            case 3:
                printf("%d\n", find_hash_value(value));
                break;
        }
    }

    return 0;
}