hash.h
#ifndef _HASH_
#define _HAHS_
#define N 15
typedef int datatype;
typedef struct node
{
datatype key;
datatype value;
struct node *next;
} listnode, *linklist;
typedef struct
{
listnode data[N];
} hash;
hash *hash_create();
int hash_insert(hash *HT, datatype key);
linklist hash_search(hash *HT, datatype key);
#endif
hash.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hash.h"
hash *hash_create()
{
hash *HT;
if ((HT = (hash *)malloc(sizeof(hash))) == NULL)
{
printf("malloc failed\n");
return NULL;
}
memset(HT, 0, sizeof(hash));
return HT;
}
int hash_insert(hash *HT, datatype key)
{
if (HT == NULL)
{
printf("HT is null\n");
return -1;
}
linklist p, q;
if ((p = (linklist)malloc(sizeof(listnode))) == NULL)
{
printf("malloc failed\n");
return -1;
}
p->key = key;
p->value = key % N;
p->next = NULL;
q = &(HT->data[key % N]);
while (q->next && q->next->key < p->key)
{
q = q->next;
}
p->next = q->next;
q->next = p;
return 0;
}
linklist hash_search(hash *HT, datatype key)
{
if (HT == NULL)
{
printf("HT is null\n");
return NULL;
}
linklist p;
p = &(HT->data[key % N]);
while (p->next && p->next->key != key)
{
p = p->next;
}
if (p->next == NULL)
{
return NULL;
}
else
{
printf("found\n");
return p->next;
}
return p;
}
demo.c
#include <stdio.h>
#include <stdlib.h>
#include "hash.h"
int main()
{
hash *HT;
int data[] = {23, 34, 14, 38, 46, 16, 68, 104, 72, 25};
int i, key;
linklist r;
if ((HT = hash_create()) == NULL)
{
return -1;
}
for (i = 0; i < sizeof(data) / sizeof(int); i++)
{
hash_insert(HT, data[i]);
}
printf("input:\n");
scanf("%d", &key);
r = hash_search(HT, key);
if (r == NULL)
{
printf("not found\n");
}
else
{
printf("index:%d %d %d\n", key, r->key, r->value);
}
return 0;
}
makefile
CC = gcc
SRC = $(wildcard *.c)
OBJ = $(patsubst %.c, %.o, $(SRC))
test:$(SRC)
$(CC) $^ -o $@ -Wall
.PHONY:clean
clean:
rm ./*.o