#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define maxsize 13
typedef struct LNode
{
int data;
struct LNode *next;
}LNode;
typedef struct
{
int length;
LNode *list[20];
}HashTable;
int Hash(int key)
{
return key%maxsize;
}
void create(HashTable *H,int Length)
{
int i;
H->length=Length;
//*(H->list)=(LNode*)malloc(sizeof(LNode)*Length);
for(i=0;i<Length;i++)
{
H->list[i]=(LNode*)malloc(sizeof(LNode)*Length);
H->list[i]->data=0;
H->list[i]->next=NULL;
}
}
int find(HashTable *H,int key)
{
int pos=Hash(key);
LNode *p=H->list[pos];
while(p->next!=NULL && p->data!=key)
p=p->next;
if(p->data==key)
return 1;
else
return 0;
}
int insert(HashTable *H,int key)
{
int pos=Hash(key);
LNode *p=H->list[pos],*s;
if(find(H,key)==1)
return 0;
else
{
s=(LNode*)malloc(sizeof(LNode));
while(p->next!=NULL)
p=p->next;
s->data=key;
s->next=NULL;
p->next=s;
return 1;
}
}
int dele(HashTable *H,int key)
{
int pos=Hash(key);
LNode *p,*pre=H->list[pos];
if(find(H,key)==0)
return 0;
else
{
p=pre->next;
while(p!=NULL && p->data!=key)
{
p=p->next;
pre=pre->next;
}
if(p==NULL)
return 0;
else
{
pre->next=p->next;
free(p);
return 1;
}
}
}
int main()
{
HashTable *H=(HashTable *)malloc(sizeof(HashTable));
int i;
create(H,maxsize);
insert(H,13);
insert(H,11);
insert(H,24);
insert(H,25);
printf("输入要查找的元素:\n");
scanf("%d",&i);
while(i!=0)
{
if(find(H,i)==1)
printf("在哈希表中!\n");
else
printf("不在哈希表中!\n");
scanf("%d",&i);
}
printf("输入要删除的元素:\n");
scanf("%d",&i);
dele(H,i);
printf("输入要查找的元素:\n");
scanf("%d",&i);
while(i!=0)
{
if(find(H,i)==1)
printf("在哈希表中!\n");
else
printf("不在哈希表中!\n");
scanf("%d",&i);
}
system("pause");
return 0;
}
模拟——哈希表(除留余数法+链地址法)
最新推荐文章于 2024-05-24 16:23:13 发布