Repository navigation
Expand file tree
/
Copy pathhash.c
More file actions
145 lines (121 loc) · 2 KB
/
Copy pathhash.c
File metadata and controls
145 lines (121 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#include <stdio.h>
#include <stdlib.h>
#define MOD 666013
typedef struct node{
int val;
struct node *next;
}node;
typedef struct list{
node *head;
}list;
typedef struct hashTable{
list **arr;
int size;
} hashTable;
list *createList()
{
list *new = malloc(sizeof(list));
new->head = NULL;
return new;
}
void insert(list *l, int x)
{
//insert as first element
node *new = malloc(sizeof(node));
new->val = x;
new->next = l->head;
l->head = new;
}
void del(list *l, int x)
{
//empty list
if(!l->head) return;
//first element
if(l->head->val == x)
{
node *del = l->head;
l->head = l->head->next;
free(del);
return;
}
node *cur = l->head, *prev;
while(cur)
{
if(cur->val == x) break;
prev = cur;
cur = cur->next;
}
//other element
if(cur)
{
prev->next = cur->next;
free(cur);
}
}
int isIn(list *l, int x)
{
node *it = l->head;
while(it)
{
if(it->val == x) return 1;
it = it->next;
}
return 0;
}
void delList(list *l)
{
node *cur = l->head, *prev;
while(cur)
{
prev = cur;
cur = cur->next;
free(prev);
}
}
hashTable *createHashTable(int size)
{
hashTable *new = malloc(sizeof(hashTable));
new->size = size;
new->arr = malloc(size * sizeof(list*));
for(int i = 0; i < size; i++)
new->arr[i] = createList();
return new;
}
void delHashTable(hashTable *h)
{
for(int i = 0; i < h->size; i++)
{
delList(h->arr[i]);
free(h->arr[i]);
}
free(h->arr);
free(h);
}
int main()
{
FILE *fin = fopen("hashuri.in", "r");
FILE *fout = fopen("hashuri.out", "w");
int nOperations, operation, x, hashVal;
hashTable *h = createHashTable(MOD);
fscanf(fin, "%d", &nOperations);
for(int i = 1; i <= nOperations; i++)
{
fscanf(fin, "%d%d", &operation, &x);
hashVal = x % MOD;
switch(operation)
{
case 1:
if(!isIn(h->arr[hashVal], x)) insert(h->arr[hashVal], x);
break;
case 2:
del(h->arr[hashVal], x);
break;
case 3:
fprintf(fout, "%d\n", isIn(h->arr[hashVal], x));
break;
}
}
delHashTable(h);
fclose(fin);
fclose(fout);
}