散列表的插入和检索(c语言实现)

#include<stdio.h>
#include<malloc.h>
int m=20;
typedef struct node
{
	int data;
	struct node *next;
}node;
typedef struct nodelist
{
	int count;
	node * start;
}nodelist;
int hash(int i)
{
	int pos=i%m;
	return pos;
}
void insert(nodelist* a,int i)
{
	int j=hash(i);
	node * bt=(node *)malloc(sizeof(node));
	bt->data=i;
	bt->next=NULL;
	if(a[j].count==0)
	{
		a[j].start=bt;
		a[j].count++;
	}
	else
	{
		bt->next=a[j].start;
		a[j].start=bt;
		a[j].count++;
	}
}
void search(nodelist *a,int x)
{
	int pos=hash(x);
	if(a[pos].count==0)
		printf("NOT EXIST!\n");
	else
	{
		int i=a[pos].count;
		int j=1;
		node *s=a[pos].start;
		while(j<=i)
		{
			if(s->data==x)
			{
				printf("EXIST!\n");
				break;
			}
			else
			{
				j++;
				s=s->next;
			}
		}
		if(j>i)
			printf("NOT EXIST!\n");
	}
}
int main()
{
	nodelist a[20];
	for(int i=0;i<20;i++)
	{
		a[i].start=NULL;
		a[i].count=0;
	}
	insert(a,2);
//	insert(a,3);
//	insert(a,22);
	search(a,24);
	return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值