Pagini recente » Profil irina_manea | JohnnyCode | Borderou de evaluare (job #2139308) | Cod sursa (job #1663993) | Cod sursa (job #3350653)
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<math.h>
#define HASHMAP_SIZE 100
#define A 0.618033
typedef struct node {
int key;
struct node* next;
}node;
void initializeHashMap(node* hashMap[]) {
for (int i = 0; i < HASHMAP_SIZE; i++)
hashMap[i] = NULL;
}
node* createNode(int value) {
node* newNode = (node*)malloc(sizeof(node));
newNode->key = value;
newNode->next = NULL;
return newNode;
}
void insertNodeInList(node** list, int value) {
node* newNode = createNode(value);
if (*list == NULL) {
*list = newNode;
return;
}
node* tail = *list;
while (tail->next != NULL)
tail = tail->next;
tail->next = newNode;
}
node* searchNodeInList(node* list, int value) {
if (list == NULL)
return NULL;
node* toFind = list;
while (toFind != NULL) {
if (toFind->key == value)
return toFind;
toFind = toFind->next;
}
return NULL;
}
void deleteNodeFromList(node** list, int value) {
if (*list == NULL)
return;
if ((*list)->next == NULL) {
*list = NULL;
free(*list);
return;
}
node* previous = *list;
node* toDelete = (*list)->next;
while (toDelete != NULL) {
if (toDelete->key == value)
break;
previous = previous->next;
toDelete = toDelete->next;
}
previous->next = toDelete->next;
toDelete->next = NULL;
toDelete = NULL;
free(toDelete);
}
double fractional(double n) {
return n - (int)n;
}
int hash(int key) {
return floor(fractional(A * key) * HASHMAP_SIZE);
}
void insertKey(node* hashMap[], int key) {
int index = hash(key);
node* find = searchNodeInList(hashMap[index], key);
if (find == NULL)
insertNodeInList(&hashMap[index], key);
}
void deleteKey(node* hashMap[], int key) {
int index = hash(key);
node* find = searchNodeInList(hashMap[index], key);
if (find != NULL)
deleteNodeFromList(&hashMap[index], key);
}
bool searchKey(node* hashMap[], int key) {
int index = hash(key);
node* find = searchNodeInList(hashMap[index], key);
return find != NULL;
}
void main(int argc, char* argv[]) {
node* map[HASHMAP_SIZE];
initializeHashMap(map);
FILE* input = fopen("hashuri.in", "r");
if (input == NULL) exit(1);
FILE* output = fopen("hashuri.out", "w");
if (output == NULL) exit(2);
int n, operation, x;
fscanf(input, "%d", &n);
for (int i = 0; i < n; i++) {
fscanf(input, "%d %d", &operation, &x);
if (operation == 1) {
insertKey(map, x);
} else if (operation == 2) {
deleteKey(map, x);
} else if (operation == 3) {
fprintf(output, "%d\n", searchKey(map, x));
}
}
fclose(input);
fclose(output);
}