-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathHashT.c
126 lines (109 loc) · 2.7 KB
/
HashT.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
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define LOAD_FACTOR 20
struct ListNode{
int key;
int data;
struct ListNode *next;
};
struct HashTableNode{
int bcount;
struct ListNode *next;
};
struct HashTable{
int tsize;
int count;
struct HashTableNode **Table;
};
struct HashTable *CreateHashTable(int size){
int i;
struct HashTable *h;
h = (struct HashTable *)malloc(sizeof(struct HashTable));
if(!h){
return NULL;
}
h->tsize = size/LOAD_FACTOR;
h->count = 0;
h->Table = (struct HashTableNode **)malooc(sizeof(struct HashTableNode *) *h->tsize);
if(!h->Table){
printf("Memory Error");
return NULL;
}
for(i=0;i<h->tsize;i++){
h->Table[i]->next = NULL;
h->Table[i]->bcount = 0;
}
return h;
}
int HashSearch(struct HashTable *h, int data){
struct ListNode *temp;
temp = h->Table[Hash(key,h->tsize)]->next;
while(temp){
if(temp->data==data)
return 1;
temp = temp->next;
}
return 0;
}
int HashInsert(struct HashTable *h, int data){
int index;
struct ListNode *temp, *newNode;
if(HashSearch(h,data)){
return 0;
}
index = Hash(key,h->tsize);
temp = h->Table[index]->next;
newNode = (struct ListNode *)malloc(sizeof(struct ListNode));
if(!newNode){
printf("Out Of Space");
return -1;
}
newNode->key = index;
newNode->data = data;
newNode->next = h->Table[index]->next;
h->Table[index]->next = newNode;
h->Table[index]->bcount++;
h->count++;
if(h->count/h->tsize > LOAD_FACTOR){
Rehash(h);
return 1;
}
}
int HashDelete(struct HashTable *h, int data){
int index;
struct ListNode *temp;
index =Hash(data,h->tsize);
for(temp=h->Table[index]->next,prev=NULL;temp;prev=temp,temp=temp->next){
if(temp->data==data){
if(prev!=NULL){
prev->next = temp->next;
}
free(temp);
h->Table[index]->bcount--;
h->count--;
return 1;
}
}
return 0;
}
void Rehash(Struct HashTable *h){
int oldsize,i,index;
struct ListNode *p, *temp;
struct HashTableNode **oldTable;
oldsize = h->tsize;
oldTable = h->Table;
h->tsize = h->tsize*2;
h->Table= (struct HashTableNode **)malloc(h->tsize*sizeof(struct HashTableNode *));
if(!h->Table){
printf("Allocation Failed");
return;
}
for(i=0;i<oldsize;i++){
for(temp=oldTable[i]->next;temp;temp=temp->next){
index = Hash(temp->data,h->tsize);
temp->next = h->Table[index]->next;
h->Table[index]->next = temp;
}
}
}