link.c
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include <stdlib.h>
#include "link.h"
/**
** 这是一个计算HASH值的算法
**/
int time33(char* arKey,int arlength){
int h = 0;
int i;
for(i=0;i<arlength;i++){
h = h*33 + (int)*arKey++;
}
return h;
}
//创建节点
struct node* createNode(char* key,char* s)
{
int node_key=0;
//强制转换,假如使用(void* value)
//char* arKey = (char*)key;
int len =strlen(key);
struct node* new_node=(struct node*)malloc(sizeof(struct node));
if(new_node==NULL)
{
printf("内存分配失败\n");
}
memset(new_node,0,sizeof(new_node));
node_key = time33(key,len);
new_node->value=node_key;
new_node->string=s;
new_node->next=NULL;
return new_node;
}
//新增节点
void add(struct node* head,char* key,char* s)
{
struct node* new_node=createNode(key,s);
while(head->next!=NULL)
{
head=head->next;
}
head->next=new_node;
}
//搜索节点
char* searchNode(struct node* head,char* key)
{
int len = strlen(key);
int node_key = time33(key,len);
while(head->next!=NULL)
{
if(head->value==node_key)
{
return head->string;
}
head=head->next;
}
return NULL;
}
//删除节点
int deleteNode(struct node* head,char* key)
{
int i=0;
int len = strlen(key);
int node_key = time33(key,len);
while(head->next->next!=NULL)
{
if(head->next->value==node_key)
{
struct node* d_node=head->next;
head->next=head->next->next;
free(d_node);
return i;
}
i++;
head=head->next;
}
return 0;
}
//主文件
int main()
{
int d1=0;
char* s1;
struct node* head=createNode("0","0");
add(head,"aa","aaa");
add(head,"bb","bbb");
add(head,"cc","ccc");
add(head,"dd","ddd");
add(head,"ee","eee");
add(head,"ff","fff");
s1=searchNode(head,"cc");
d1=deleteNode(head,"bb");
return 0;
}
link.h
#define HASHSIZE 13
struct node{
int value;
char* string;
struct node* next;
};