模拟——哈希表(除留余数法+链地址法)

#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;
}
  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值