-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathhashing.c
73 lines (58 loc) · 1.38 KB
/
hashing.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
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
struct Node{
int data;
struct Node *next;
};
struct HashTable{
struct Node *chain[SIZE];
};
void init(struct HashTable *ht){
for (int i = 0; i < SIZE; i++){
ht->chain[i] = NULL;
}
}
void insert(struct HashTable *ht, int value){
int key = value % SIZE;
struct Node *newNode = malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
if (ht->chain[key] == NULL){
ht->chain[key] = newNode;
}
else{
struct Node *temp = ht->chain[key];
while (temp->next){
temp = temp->next;
}
temp->next = newNode;
}
printf("Entered value %d added to hash table\n", value);
}
void printHashTable(struct HashTable *ht){
for (int i = 0; i < SIZE; i++){
printf("chain[%d]-->", i);
struct Node *temp = ht->chain[i];
while (temp != NULL){
printf("%d -->", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
}
void main()
{
struct HashTable ht;
init(&ht);
int num, val;
printf("Enter the number of elements: ");
scanf("%d", &num);
for (int i = 0; i < num; i++){
printf("Enter element %d: ", i + 1);
scanf("%d", &val);
insert(&ht, val);
}
printf("\n\nThe hash table is:\n\n");
printHashTable(&ht);
}