#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma wanring (disable : 4996)
typedef struct node
{
int value;
struct node* next;
}node;
typedef struct hashTable
{
node** head;
int size;
}hashTable;
int hashInt(int value, int size);
int hashString(char* str, int size);
void createHash(hashTable* p, int size);
void addKey(hashTable* p, int key);
int hashInt(int value, int size)
{
return value % size;
}
int hashString(char* str, int size)
{
int total = 0;
for(int i = 0; i < strlen(str); i++)
{
total += str[i];
}
return total % size;
}
void createHash(hashTable* p, int size)
{
p->head = (node**)calloc(size, sizeof(node*));
p->size = size;
}
void addKey(hashTable* p, int key)
{
int hashValue = hashInt(key, p->size);
node* newNode;
newNode = (node*)malloc(sizeof(node));
newNode->value = key;
newNode->next = NULL;
if(p->head[hashValue] == NULL)
{
p->head[hashValue] = newNode;
return;
}
newNode->next = p->head[hashValue];
p->head[hashValue] = newNode;
}
void displayHashTable(hashTable* p)
{
node* curNode;
for(int i = 0; i < p->size; i ++)
{
curNode = p->head[i];
printf("HashTable[%d] => ", i);
while (curNode)
{
printf("%d ", curNode->value);
curNode = curNode->next;
}
puts("");
}
}
int main()
{
hashTable ht;
createHash(&ht, 7);
addKey(&ht, 77);
addKey(&ht, 7);
addKey(&ht, 36);
addKey(&ht, 92);
addKey(&ht, 15);
addKey(&ht, 79);
addKey(&ht, 83);
displayHashTable(&ht);
return 0;
}