-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhashing.c
88 lines (73 loc) · 1.76 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
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
struct Node {
int data;
struct Node* next;
};
struct Node* hashT[SIZE];
void inhashT() {
for (int i = 0; i < SIZE; i++) {
hashT[i] = NULL;
}
}
int hashfunc(int key) {
return key % SIZE;
}
void insert(int key) {
int index = hashfunc(key);
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = key;
newNode->next = NULL;
if (hashT[index] == NULL) {
hashT[index] = newNode;
} else {
struct Node* temp = hashT[index];
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
void disphashT() {
for (int i = 0; i < SIZE; i++) {
printf("Index %d:", i);
if (hashT[i] == NULL) {
printf(" ----\n");
} else {
struct Node* temp = hashT[i];
while (temp != NULL) {
printf("%d -->", temp->data);
temp = temp->next;
}
printf(" NULL\n");
}
}
}
int main() {
inhashT();
int choice, key;
do {
printf("\nMenu:\n");
printf("1.Insert an Element\n2.Display Hash Table\n3.Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter the Element to Insert: ");
scanf("%d", &key);
insert(key);
break;
case 2:
printf("\nHash Table : \n");
disphashT();
break;
case 3:
break;
default:
printf("Invalid choice!\n");
break;
}
} while (choice != 3);
return 0;
}