6 #define HTABLE_SIZE 100
13 /* Function prototypes */
14 hnode_t
*htable_alloc(unsigned int size
);
15 void htable_free(hnode_t
*htable
[], unsigned int size
);
16 void htable_insert(hnode_t
*htable
[], char *str
, unsigned int pos
);
17 unsigned int htable_search(hnode_t
*htable
[], char *str
);
18 unsigned int htable_mkhash(char *str
);
24 myhtable
= htable_alloc(HTABLE_SIZE
);
26 printf("=========================\n");
28 htable_insert(&myhtable
, "stathis", htable_mkhash("stathis"));
31 printf("%d\n", htable_search(&myhtable
, "stathis"));
34 htable_free(&myhtable
, HTABLE_SIZE
);
39 hnode_t
*htable_alloc(unsigned int size
)
44 if ((pnode
= malloc(size
* sizeof *pnode
)) == NULL
) {
49 for (i
= 0; i
< size
; i
++) {
57 void htable_free(hnode_t
*htable
[], unsigned int size
)
61 for (i
= 0; i
< size
; i
++) {
65 void htable_insert(hnode_t
*htable
[], char *str
, unsigned int pos
)
70 if (htable
[pos
]->str
== NULL
) {
71 htable
[pos
] = htable_alloc(1);
72 if ((htable
[pos
]->next
->str
= malloc(sizeof(strlen(str
)))) == NULL
)
74 strcpy(htable
[pos
]->next
->str
, str
);
77 /* Collision resolution */
78 for (pnode
= htable
[pos
]; pnode
!= NULL
; pnode
= pnode
->next
) {
79 if (pnode
->next
== NULL
) {
80 pnode
->next
= htable_alloc(1);
81 if ((pnode
->next
->str
= malloc(sizeof(strlen(str
)))) == NULL
)
83 strcpy(pnode
->next
->str
, str
);
90 unsigned int htable_search(hnode_t
*htable
[], char *str
)
95 pos
= htable_mkhash(str
);
97 if (strcmp(htable
[pos
]->str
, str
) == 0)
100 /* Search across the chain */
101 for (pnode
= htable
[pos
]; pnode
!= NULL
; pnode
= pnode
->next
)
102 if (strcmp(pnode
->str
, str
))
109 unsigned int htable_mkhash(char *str
)
112 unsigned int i
, hash
= 5381;
114 for (i
= 0; i
< strlen(str
); i
++)
115 hash
= ((hash
<< 5) + hash
) + str
[i
];
117 return (hash
& 0x7FFFFFFF) % HTABLE_SIZE
;