-
Notifications
You must be signed in to change notification settings - Fork 1
/
HASH.C
executable file
·133 lines (103 loc) · 2.21 KB
/
HASH.C
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
#include <stdio.h>
#include <alloc.h>
#include <limits.h>
#include "structs.h"
#include "hash.h"
int counter = 0;
int getCounter(){
return counter;
}
TABLE * CreateHashtable(int size)
{
int i;
TABLE *hashtable;
if ( (hashtable = (TABLE *) malloc( sizeof(TABLE))) == NULL){
printf("HASH: Cant allocate memory!\n");
exit(1);
}
if ( (hashtable->data = (ENTRY **) malloc(size * sizeof(ENTRY *))) == NULL){
printf("HASH: Cant allocate memory!\n");
exit(1);
}
for (i = 0; i < size; i++)
{
hashtable->data[i] = NULL;
}
hashtable->size = size;
return hashtable;
}
int GetHash(TABLE *hashtable, char *key)
{
unsigned long int hashval=0;
int i = 0;
while (hashval < ULONG_MAX && i != strlen(key))
{
hashval = hashval << 8;
hashval += key[i];
i++;
}
return hashval % hashtable->size;
}
ENTRY *NewPair(char *key, int value)
{
ENTRY *newpair;
if( (newpair = malloc(sizeof(ENTRY)) ) == NULL)
{
return NULL;
}
if ( (newpair->key = strdup(key)) == NULL){
return NULL;
}
counter++;
newpair->value = value;
newpair->next = NULL;
return newpair;
}
void Set(TABLE *hashtable, char *key, int value)
{
int bin = 0;
ENTRY *newpair = NULL;
ENTRY *next = NULL;
ENTRY *last = NULL;
bin = GetHash(hashtable, key);
next = hashtable->data[bin];
while (next != NULL && next->key != NULL && strcmp(key,next->key) > 0){
last = next;
next = next->next;
}
if ( next != NULL && next-> key != NULL && strcmp(key, next->key) == 0)
{
next->value = value;
}
else
{
newpair = NewPair(key, value);
if (next == hashtable->data[bin] ){
newpair->next = next;
hashtable->data[bin] = newpair;
} else if (next == NULL) {
last->next = newpair;
} else {
newpair->next = next;
last->next = newpair;
}
}
}
int Get(TABLE *hashtable, char *key)
{
int bin = 0;
ENTRY *pair;
bin = GetHash(hashtable, key);
pair = hashtable->data[bin];
while(pair != NULL && pair->key !=NULL && strcmp(key, pair->key) > 0) {
pair = pair->next;
}
if (pair == NULL || pair->key == NULL || strcmp(key,pair->key) != 0){
return NULL;
}
else
{
return pair->value;
}
}