-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhash_chaining.c
More file actions
115 lines (105 loc) · 1.77 KB
/
Copy pathhash_chaining.c
File metadata and controls
115 lines (105 loc) · 1.77 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
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
typedef struct Node Node;
struct Node{
int key;
int value;
Node* next;
};
int hash(int key);
int search(int key);
void insert(int key, int value);
void delete(int key);
void traverse();
Node** hash_table;
int main(){
hash_table = (Node**)malloc(sizeof(Node*)*SIZE);
int i;
for(i=0;i<SIZE;i++){
hash_table[i] = NULL;
}
traverse();
insert(1,1);
traverse();
insert(2,2);
traverse();
insert(3,3);
traverse();
insert(4,4);
traverse();
insert(5,5);
traverse();
insert(6,6);
traverse();
delete(1);
traverse();
delete(6);
traverse();
}
int hash(int key){
return key % 5;
}
int search(int key){
int hash_code = hash(key);
Node *p = hash_table[hash_code];
while(p){
if(p->key == key){
return p->value;
}
p = p->next;
}
return -1;
}
void insert(int key, int value){
int hash_code = hash(key);
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->key = key;
newNode->value = value;
newNode->next = NULL;
Node *p = hash_table[hash_code];
if(p==NULL){
hash_table[hash_code] = newNode;
return;
}
while(p->next){
p = p->next;
}
p->next = newNode;
}
void delete(int key){
int hash_code = hash(key);
Node *p = hash_table[hash_code];
if(p==NULL){
return;
}
if(p->key == key){
hash_table[hash_code] = p->next;
free(p);
return;
}
Node *prev = p;
p = p -> next;
while(p){
if(p->key == key){
prev->next = p->next;
free(p);
return;
}
prev = p;
p = p -> next;
}
}
void traverse(){
int i;
for(i=0;i<SIZE;i++){
printf("hash_code:%ld: ",i);
Node *p = hash_table[i];
while(p){
printf("%ld ",p->value);
p = p->next;
}
printf("\n");
}
printf("\n");
}