-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashTable.c
More file actions
99 lines (87 loc) · 1.72 KB
/
Copy pathHashTable.c
File metadata and controls
99 lines (87 loc) · 1.72 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
#include<stdio.h>
#include<stdlib.h>
#define MAX 20
typedef struct {
int key;
int data;
}DataItem;
DataItem* hashArray[MAX];
DataItem* dummyItem;
DataItem* item;
int hashCode(int key)
{
return (key % MAX);
}
void display()
{
int i = 0;
for(i=0; i<MAX; i++)
{
if(hashArray[i] != NULL)
printf("(%d, %d))",hashArray[i]->key,hashArray[i]->data);
else
printf("(~,~)");
}
printf("\n");
}
void insert(int key, int data)
{
item = (DataItem *)malloc(sizeof(DataItem));
item->data = data;
item->key = key;
int hashIndex = hashCode(key);
while(hashArray[hashIndex] != NULL && hashArray[hashIndex]->key != -1)
{
hashIndex++;
hashIndex % MAX;
}
hashArray[hashIndex] = item;
}
DataItem* search(int key)
{
int hashIndex = hashCode(key);
while(hashArray[hashIndex] != NULL)
{
if (hashArray[hashIndex]->key == key)
{
return hashArray[hashIndex];
}
hashIndex++;
hashIndex %= MAX;
}
return NULL;
}
void delete(int key)
{
int hashIndex = hashCode(key);
while(hashArray[hashIndex] != NULL)
{
if (hashArray[hashIndex]->key == key)
{
item = hashArray[hashIndex];
free(item);
hashArray[hashIndex] = dummyItem;
return;
}
hashIndex++;
hashIndex %= MAX;
}
}
int main()
{
dummyItem = (DataItem *)malloc(sizeof(DataItem));
dummyItem->data = -1;
dummyItem->key = -1;
insert(5,55);
insert(1,11);
insert(4,44);
insert(3,33);
insert(6,66);
insert(7,77);
insert(2,22);
display();
delete(3);
delete(7);
display();
return 0;
}