Cod sursa(job #282207)

Utilizator tomescu_alinTomescu Alin tomescu_alin Data 17 martie 2009 06:55:32
Problema Hashuri Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 2.27 kb
/*
	Author:	Alin Tomescu
	Webpage:	http://alinush.isgreat.org
	Copyright:	Free to use and distribute as long as this note is kept
	Date:		6:54 AM Tuesday, March 17, 2009
*/

//	Who said C ain't fast?
#include <stdio.h>
#include <stdlib.h>

typedef unsigned int uint;
typedef unsigned long ulong;
typedef unsigned short int bool;
#define true 1
#define false 0

//	A linked list node
typedef struct node {
	ulong data;
	struct node * next;
} node;

#define HASH_PRIME 666013
#define HASH(X) ((X)%HASH_PRIME)
node * hashTable[HASH_PRIME];

void prepend(node * list[], ulong data) {
	ulong hash = HASH(data);
	node * traveler = list[hash];
	bool found = false;
	
	while(traveler) {
		if(traveler->data == data) {
			found = true;
			break;
		}
		
		traveler = traveler->next;
	}
	
	if(!found) {
		traveler = malloc(sizeof(node));
		traveler->data = data;
		traveler->next = list[hash];
		list[hash] = traveler;
	}
}

bool find(node * list[], ulong data) {
	ulong hash = HASH(data);
	node * traveler = list[hash];
	bool found = false;
	
	while(traveler) {
		if(traveler->data == data) {
			found = true;
			break;
		}		
		traveler = traveler->next;
	}
	
	return found;
}

void erase(node * list[], ulong data) {
	ulong hash = HASH(data);
	node * traveler = list[hash];
	bool found = false;
	
	while(traveler) {
		if(traveler->data == data) {
			found = true;
			break;
		}		
		traveler = traveler->next;
	}
	
	if(found) {
		//	Copy the data from the head into the node to be removed
		traveler->data = list[hash]->data;
		//	We are now going to delete the head, since we already saved the data in it
		//	Copy a reference to the head pointer into traveler
		traveler = list[hash];
		//	Advance the head pointer
		list[hash] = list[hash]->next;
		//	Delete the traveler
		free(traveler);
	}
}

int main() {
	freopen("hashuri.in", "r", stdin);
	freopen("hashuri.out", "w", stdout);
	
	ulong n, operation, param, i;
	scanf("%lu",&n);
	
	for(i = 0; i < n; i++) {
		scanf("%lu%lu", &operation, &param);
		
		switch(operation) {
			case 1:
				prepend(hashTable, param);
				break;
			case 2:
				erase(hashTable, param);
				break;
			case 3:
				printf("%u\n", find(hashTable, param));
				break;
		}
	}
	
	return 0;
}