Pagini recente » Cod sursa (job #1708954) | Cod sursa (job #605020) | Cod sursa (job #1994085) | Cod sursa (job #1466897) | Cod sursa (job #1850751)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#define tableSize 1999994
#define MOD 1999993
struct item{
int data;
struct item* next;
};
struct item* HashTable[tableSize];
int key(int x){
int h = x % MOD;
return (h) ? h : MOD;
}
void Insert(int x){
int index = key(x);
if(HashTable[index] == NULL){
HashTable[index] = (struct item*)malloc(sizeof(struct item));
HashTable[index] -> data = x;
HashTable[index] -> next = NULL;
}else{
struct item* ptr = HashTable[index];
struct item* newItem = (struct item*)malloc(sizeof(struct item));
newItem -> data = x;
newItem -> next = NULL;
while(1){
if(ptr -> data == x){
return;
}
if(ptr -> next == NULL){
break;
}
ptr = ptr -> next;
}
ptr -> next = newItem;
}
}
int Search(int x){
int index = key(x);
struct item* ptr = HashTable[index];
while(ptr != NULL){
if(ptr -> data == x){
return 1;
}
ptr = ptr -> next;
}
return 0;
}
void Delete(int x){
int index = key(x);
struct item* delPtr, *P1, *P2;
if(HashTable[index] == NULL){
return;
}
if(HashTable[index] -> data == x){
delPtr = HashTable[index];
HashTable[index] = (HashTable[index] -> next == NULL) ? NULL : HashTable[index] -> next;
free(delPtr);
return;
}
P1 = HashTable[index] -> next;
P2 = HashTable[index];
while(P1 != NULL && P1 -> data != x){
P2 = P1;
P1 = P1 -> next;
}
if(P1 == NULL){
return;
}
delPtr = P1;
P1 = P1 -> next;
P2 -> next = P1;
free(delPtr);
}
int main() {
freopen("hashuri.in", "r", stdin);
freopen("hashuri.out", "w", stdout);
int T, op, x;
scanf("%d", &T);
while(T--){
scanf("%d", &op);
scanf("%d", &x);
if(op==1){
Insert(x);
}else if(op==2){
Delete(x);
}else if(op==3){
printf("%d\n", Search(x));
}
}
return 0;
}