forked from anand-b/Compiler
/
map.cpp
136 lines (134 loc) · 2.33 KB
/
map.cpp
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#include<stdio.h>
#include<stdlib.h>
#include<stddef.h>
#include<string.h>
struct list
{
struct node *link;
int count;
}*lis;
struct node
{
struct node *link;
char *name;
int *addr;
};
typedef struct list l;
typedef struct node n;
// returns the index
int hashUtil(char *name)
{
int addition=0;
for(int i=0;name[i]!='\0';i++)
addition+=(int)name[i];
return addition%200;
}
n* createNode(char *name,int *addr)
{
n *temp=(n*)malloc(sizeof(n));
temp->link=NULL;
temp->name=name;
temp->addr=addr;
return temp;
}
// 1 success 0 fail
int insert(l *list,char *name,int *addr)
{
int index=hashUtil(name);
list[index].count++;
if(list[index].link==NULL)
{
list[index].link=createNode(name,addr);
}
else
{
n *temp=list[index].link,*prev=list[index].link;
while(temp!=NULL)
{
prev=temp;
temp=temp->link;
}
prev->link=createNode(name,addr);
}
return 1;
}
void remove(l *list,char *name)
{
int index=hashUtil(name);
n *temp,*prev;
if(list[index].count==1)
{
temp=list[index].link;
free(temp);
list[index].link=NULL;
}
else
{
if(list[index].link->name==name)
{
temp=list[index].link;
list[index].link=list[index].link->link;
free(temp);
}
else
{
temp=list[index].link->link;
prev=list[index].link;
while(temp!=NULL && temp->name!=name)
{
prev=temp;
temp=temp->link;
}
prev->link=temp->link;
free(temp);
}
}
list[index].count--;
}
void printUtil(l *list,int index)
{
n *temp=list[index].link;
while(temp!=NULL)
{
printf("%s ",temp->name);
temp=temp->link;
}
printf("\n");
}
void freeListUtil(n *node)
{
if(node==NULL)
return;
else
{
freeListUtil(node->link);
}
n *temp=node;
free(temp);
}
void freeList(l *list)
{
for(int i=0;i<200;i++)
{
freeListUtil(list[i].link);
list[i].link=NULL;
}
}
int main()
{
lis=(l*)malloc(sizeof(l)*200);
l *lis2=(l*)malloc(sizeof(l)*200);
int a,b,c;
char n1[6]="a",n2[6]="b",n3[6]="c",n4[5]="sfd";
for(int i=0;i<200;i++)
{
lis[i].link=NULL;
lis[i].count=0;
}
insert(lis,n1,&a);
insert(lis,n2,&b);
insert(lis,n3,&c);
insert(lis,n4,&a);
freeList(lis);
printUtil(lis,97);
}