-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashSet.c
More file actions
87 lines (80 loc) · 1.93 KB
/
Copy pathHashSet.c
File metadata and controls
87 lines (80 loc) · 1.93 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
#include "header.h"
int hash ( int key ){
return key % TABLE_SIZE ;
}
HashSet* createHashSet() {
HashSet*obj=(HashSet*)malloc(sizeof(HashSet));
if(obj==NULL){
printf("\nMemory allocation failed\n");
}
for(int i=0 ; i < TABLE_SIZE ; i++) {
obj->table[i]=NULL;
}
printf("\nHashSet created successfully\n");
return obj;
}
void addHashSet(HashSet*obj,int key) {
int index=hash(key);
if(hashSetContains(obj,key)){
printf("\nElement Already present in the set\n");
return;
}
Node*newNode=(Node*)malloc(sizeof(Node));
if(newNode==NULL){
printf("\nMemory allocation failed\n");
}
newNode->key=key;
newNode->next=obj->table[index];
obj->table[index]=newNode;
printf("\nElement added to the Set successfully\n");
}
void removeHashSet(HashSet*obj,int key){
int index=hash(key);
Node*cur=obj->table[index],*prev=NULL;
while(cur){
if(cur->key==key){
if(prev){
prev->next=cur->next;
}else{
obj->table[index]=cur->next;
}
free(cur);
return;
}
prev=cur;
cur=cur->next;
}
printf("\nElement removed successfully\n");
}
bool hashSetContains(HashSet*obj,int key){
int index=hash(key);
Node*cur=obj->table[index];
while(cur){
if(cur->key==key){
return true;
}
cur=cur->next;
}
return false;
}
void displayHashSet(HashSet*obj){
for(int i=0;i<TABLE_SIZE;i++){
Node*cur=obj->table[i];
while(cur){
printf("\n%d",cur->key);
cur=cur->next;
}
}
}
void deleteHashSet(HashSet*obj){
for(int i=0 ; i<TABLE_SIZE ;i++){
Node*cur=obj->table[i];
while(cur){
Node*temp=cur;
cur=cur->next;
free(temp);
}
}
free(obj);
printf("\nHashSet deleted Successfully\n");
}